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

288

Upload: others

Post on 21-May-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

openandclosethe

Ifyourunthesameapponalarge-screentabletinlandscapeorientationtheUIforeachFragmentappearswiththemasteranddetailpanessidebysideasshownbelow

Using a fragment

ThegeneralstepstouseaFragment

1 Createae bcla of Fragment2 Createaeayoutforthe Fragment3 AddtheFragment

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

C aa ]eT n לא

-screate e

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

TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids

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

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

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 2: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Ifyourunthesameapponalarge-screentabletinlandscapeorientationtheUIforeachFragmentappearswiththemasteranddetailpanessidebysideasshownbelow

Using a fragment

ThegeneralstepstouseaFragment

1 Createae bcla of Fragment2 Createaeayoutforthe Fragment3 AddtheFragment

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

C aa ]eT n לא

-screate e

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

TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids

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

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

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 3: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

TipTheFragmentclasscontainsotherlifecyclecallbackmethodt ooverridbesids

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

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

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 4: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

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

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

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 5: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

HoweveraFragmentcantcommunicatedirectlywithanotherFragmentAll

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 6: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

SimpleFragmentfragment=SimpleFragment

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 7: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

21 App widgetsContents

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 8: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

SomewMeee eeeeoee eMeemeeeeom

eee eeeee memeMeowMeeeeo MMo o eeMeeeoow

oeMee

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 9: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

NewAppWidgetConfigurationActivityjavaisaddedtoyourprojectTheAndroidmanifestisupdatedtoincludetheproviderandc figurati activityclasses

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

eeded)andtoplacethewidgetintherightnumberofcells theh escreen

Theproviderinfoisa- XMLresourcelocatedintheresxmlfolderanditc tainsasingle

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 10: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ltLinearLayoutxmlnsandroid=httpschemasandroidcomapkresandroid

androidlayout_width=match_parent

androidlayout_height=match

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 11: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ltdimenna

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 12: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

publicvoidonUpdate(Contextcontext

AppWidgetManagerappWidgetManagerint[]appWidgetIds)

Createanewexplicitintentobject

Intentintent=newIntent(contextMainActivit a

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

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

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 13: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

$oaddthewidgetconfigurationactivitytoyourprojectwhenyouinitiallycreatethewidgetinAndroidStudioselecttheCon n nalhhn t racn

Ccr e r n

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

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 14: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Detecting sensors at runtime

IfyourappusesaspecifictypeofsensorbutdoesntrelyonityoucanusethesensorframeworktodetectthesensoratruntimethenturnofforturnonappfeaturesasappropriateForexampleaweatherappmightusethetemperaturesensorpressuresenso

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 15: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Override

publicvoidonSensorChanged(SensorEventsensorEvent)

otosovedh)nghereivsensordadaChange

sssbgssssbsssbssssbbbssonSensorChanged(bsbsssbsssbssssbsssbbsgsbbsgssbsbbbbs

b

bsbssgsbssssbsssbbss

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 16: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

32 Motion and position senso

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 17: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Understanding device rotationIfyourappdrawsviewsonthescreeninpositions asedonsensordatayouneedtotransformthesensorscoordinatesystem(whichdoesnotrotate)withthescreenoractivityscoordinatesystem(whichdoesrotate)

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

The et Rot at i on( )e od returnsoneoffourintegerconstants

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 18: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Follow the Performance Improv

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 19: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ABroadcastReceiverhasntfinishedexecutingwithin10seconds

TopreventANRsfromhappeningforthisreasonusebroadcastreceiversonlyfortheirintendedpurposeBroadcastrec

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 20: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Learn moreAndroiddeveloperdocumentation

BestPracticesforPerformancePerformanceProfilingTools(thelandingpageforallthetools)AndroidProfilerSearchdeveloperandroidcomforperformanceforafulllistofthelatestperformancedocs

Articles

YouYourAppandAndroidPerformance

яel

dAndfooate

YoҧroidPerformance

r tsp ᴵlnce

l rrmatr urA

t r

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 21: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

41 Rendering and layoutContents

MinimizeoverdrawSimplifycomplexviewhierarchiesRelatedpracticalsLearnmore

TheAndroidDeveloperFundamentalscoursetalkedabouthowtomakeyourappslookinterestingandvisuallycompellingusingMaterialDesi idelinesandittau tyouhowtousetheLayoutEdi

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 22: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Forexampleanappmightdrawastackof52overlappingcardswithonlythelastcardfullyvisibleCompletelydrawingthe51cardsthatareunderneathandpartiallycoveredisan

exampleofoverdraw

Themostlikelysympt dy willseeinanappwithoverdrawisslowrenderingandstutteringanimationsThisisthemostgenericofsympt dSinceoverdrawiscop onandstraightforwardt testformakeitahabitt checkforiteverytimey changethe

eewsofy rapp

Ifatanypointy rappisdrawingsopthingthattheuserdoesnotsee negɞ

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 23: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Profile GPU Rendering

Runth

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 24: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

3 ClickAndroidandLintintheright-handpane4 Selectorclearinspectioncheckboxesasdesired

ThefollowingaresomeofthelintinspectionsrelatedtotheviewhierarchyTheyarelistedunderAndroid gt Lint gt PerformanceintheEditor gt Inspectionspre rences

Node can be replaced by a T

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 25: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

theparentofadeep

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 26: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

AnalyzingwithProfileGPURendering

RRendering

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 27: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

43 Best practices network batterycompressionContents

RadiosNetworkandbatterybestpracticesOptimizingimages

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 28: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

InsideyourmobiledeviceisasmallpieceofhardwarethatsessentiallyaradioThepurposeofthisradioistocommunicatewithlocalcelltowersandtransmitdataHoweverthisradioisnotalwaysactiveanddrawingpowerItstartsinapowereddownstateandwhenthedeviceneedstosenddatatheradioturnsonandtransfersthedataAfterthedatapacketissent

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 29: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ConnectivityManagercm=

(ConnectivityManager)this

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 30: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

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

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

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 31: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Themoststraightforwardsolutionistopicksomenon-maximumvalueandusethatvalueHoweverbeawarethatthequalityvalueaffectseveryimagedifferentlyWhileaqualityof75forexamplemaylookfineonmostimagestheremaybesomecasesthatdonotfareaswellYoushouldmakesuretotestyourchosenmaximumvalueagainsta

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 32: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

YourappshouldnotdownloadanyimagemorethanonceImageloadinglibr

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 33: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

43Bestpracticesnetworkbatterycompression

112

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

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

values-fr-rFRdire

Why default resources are important

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

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

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

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

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

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

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

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

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

themi orM he llioo la

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

roti

l e li on aeoo h

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

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

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

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

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

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

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

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

X V H U V H H V

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

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

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

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

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

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

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

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 34: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

51 Languages and layoutsContents

UnderstandinglanguageandlocalesettingsPreparinganappforlocalizationUsingthe

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

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

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

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

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

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

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

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

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 35: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Todecidewhichlanguagesto

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 36: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Youmayalsoneedtoidentifymediaresourcessuchasaudioandvideothatneedcaptions

orsubtitles

Forexampleinthefigureabove

1 App nameThechoia oftranslatingtheappnameisuptoyouManyappsaddtranslatednamessothattheusersinotherlanguagesunderstandtheappspurposeandcanfindtheappinGooglePlayintheirownlanguagesAppsthatuseb

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 37: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

usecurrencyexchangerates9 Image tie` to a localeYoucanchangeanimagedependingonthelocaleInthis

examplethelocalecountrysflagappears

PipPhefloatingactionbuttonatthebottomofthescreeninthisexampledoesnotneedtobeadjustedforanRPLlanguagebecauseitfloatsonthescreenandisadjustedautomaticallybyAndroidslayoutmirroringfeature

PhefollowingfigureshowsthesameappintheEnglishlanguageandUSlocale(left)inFrenchintheFrancelocale(center)andinHebrewanRPLlanguageintheIsraellocale(right)

Best practices for localizing text

KeeptextseparatedfromtherestofyourappNeverembedtextincoCcedilḸtTocreatestringresourcesforotherlanguagesusetheAndroidStudioPranslationsEditorwhichautomaticallyplacesstringsxmlfilesintoappropriatelynameddirectorieswithintheappprojectsproject_nameappsrcmainresdirectoryDontconcatenatepiecesoftexttomakeasentenceorphrasePhepiecesmaynotbeintheproperorderinthetranslatedversionofthesentenceorphraseIfyoumustcombinepiecesoftextuseformatstringsasplaceholdersanduseStringformat()tosupplytheargumentstocreatethecompletedstringFormatstringsareaconvenientwaytobuilduponestringthathasvariablecontentFordetails

onusingformatstringsceeAndroidSDKauickPipFormattingResourceStringsPoensurethatformatstringsarenottranslatedusedtheP(Piffgplaceholdertagto

markitasdescribedinthe

markmeccagepartsthatshoeldnotbgtranslatec

cectioo

ofLocalicingwithResourceseaLanguagesandlayoutd

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 38: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Addressing design and layout issues

Fittingdesig elemeosaogotraglaedtextisacha g Th elemeosogth desig ao glogg fitaogotraglaed

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 39: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

anothercultureAvoidjargonregionalphrasesandmetaphorsFormxamplbrvbarusersmaynotmnowenoughaboutmmericanbasebalccediltounderstand nockingitmutmfmhepark arm r d

slamhef lccedilo ingare ipsonho topreparemedi insluding r hicsandimagus ea are fmrocs culturaldif ferunsesasnotmlccedilimagusandcymbolscarry hecamemeaningacrocsb rders apsfla sccediloca ionnamesandculturalhist rical dp liticalreferunsesmaybe f fensive ousersin otherc un ronotmnslude xtmithinimagusbecauseitmsnotmasily r sla dnslude r men sin hec ngsxmccedilfile ha y ucundmutmr r sla ionin arder odescribe he r xtmn ahicheachc ngmsused his nf rma ion ilccedilbe nvaluable ohe r sla rmndmucultinbe rau lity r sla ionr a oenuse ndroid tudios o dd langu gu oy urmppandcreahec ngmuc ursesf r he angu guouse he pun he fileandclick helinkinhe oprightc rnur ry u nuse shor cu right click hefilemndmelecdunr a m he

r a m

puns ith ro f reachruc ursekuyandi sdefau tvaluu

angu gusand ay u s

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 40: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Adjusting layouts for

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 41: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Tote

te

e

e ee e et

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 42: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

LocalizingwithResourcesLocalizationchecklistLanguageandLocaleTestingforDefaultResources

MaterialDesignUsability-Bidirectionality

AndroidDevelopersBlog

AndroidDesignSupportLibraryNativeRTLsupportinAndroid42

AndroidPlayConsoleTranslateamplocalizeyourapp

VideoWelcometofrac34llefrac34randLocalizaap to l l ҧ

rc ӑLanguigt n ul Icircc ilitt rc ט

rc ᴒrc ᴸgeNi tp Ɗd ang geidaR p ľ

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 43: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

UK

Androidprovidesclassesandmethodsyoucanusetoapplytheformatoftheuser-chosenlocaleortouseaformatfromanotherlocaleStorealldatafortheappinadefaultformatandusethe

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 44: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

TheDirectory namenowincludesalocalizationqualifierthatspecifiesalanguageandoptionallyaregionThelocalizationqualifierisatwo-letterISO639-1languagecodesuchas9- ucl tie0a lʎoptiona l na

a

isa

-lett

Ieras9- a l tie0l

Tu Tl na

weer r u o l theti a ee r t iafi rth incluhelocali

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 45: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

values-fr-rFRdire

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 46: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Why default resources are important

Donotassumethatthedevicerunningyourappisusingoneofthebppisuo opisusot ai g p pcerunnin ece uev s suo ms thede r r sume i u aeems edot r r evu apiquest pisuse ssede e ayo thsumd us frac34de uo ms thet us mt gr mp t ruau uototgu i appisuo s thume i an t i g prapdett appi n us m ce pisuse rbumot gbruppi p

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 47: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

itemstogetherishelpfularuserswh=haIcircelowvision=rtroubleacusing=neacutehescreen

T=uch regargets

Touch regamgetsamethepamtsoathescreenthaeacuteresp=ndt=userinpfrac34tTheyextendbey=ndthevisual

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 48: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Youshouldtestyourappmeensurethatitbehavestheway

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 49: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

IfyoutargetyourapptoAndroid42(APIlevel17)orhigherus

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 50: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Thesetwoimagesshowexamplesoftextsetagainsmagalackorwhitemackground ThetextattheleftshowhighercontrasmOntherightthetextissetamagaowercontrasmwhimishardertoread emarativeelementssumasmogosmontneut tomeetminimumcontrasmratios vensoiv

demarativeelementsprovit eimportantinformationmakesuretheymreeasymot istinguish ee owcoangoeu naov

ornts rmaaive aiist urea roet mlaiialeowmntt t oovi tio

h owcoangoeu t symtit eo phtea owcot st oftmmnd mnai ecot inoaet fheymtoar

h owceoetumntiveelet eeo a

t e rea ngoeut g tamnao u taoymtiveelnd mnpnao el ino

oumnentspr sofea ec es mno

t wdirnoyma h mwl o mwhiti oshowexaletnthe hes ostow ampl o

tce gsmmnostow t symomae oar

h owceoetuataoe hes t e mnaew amo t eCcedilḸ g ialeow ghtoaetostow t syml ineow gof l howohe t

amnaeou taow ght

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 51: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Lint

AndroidStudioshowslintwarningsforvariousaccessibilityissuesandprovideslinkstotheplacesinthesourcecodecontainingtheseissuesForexamp

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 52: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

71 Location servicesContents

IntroductionS

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 53: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

1 OpenAndroidStu

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 54: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

2 Callthe

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 55: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Creating a LocationRquest object

Ifyourappre iresprecisetr ki th i olvesperiodicupd esyou edtocre eaLocationquest objeceacuteth c= t re ireme soft loc io upd esT fusedloc io providerattemptstob c loc io re estsfromdiffere appstoget ri ordertopreserveb tery

T optio youc urfora Locationquest i lud

omioRetoo

a roe uo npd esc ooforasptos

ut leridetpn= etse

P

mittstoRetoo

ҷc io rζ ur oprfpd es c

leesc

e es

th c prpu ests

dtf

a

ӄoskisara e

stoRsetoo miseonoioo

SeonoiontotR

nnenm metmľTetr ur

io thbe ests

loc ion

f f

Seonoionomonm metm

Tetr ur

io thbe ests

c

lerts

c

e iseeloc ion

Seonoi onn nn

Tetr ur

io thbe ests

lheoss

ooe iseon

phee oftppsomies

uoys

tifomenyT nl ueoerdttefpeetoss

ooftphee

usis

uoyhbeoeeenostfsney

Acirc

ᴦ s

c

hbe s

loc ion

Tn tr ur

io youapps

b

ect nofeeap uc ion

dttosts

c

ft ranion

io eet

t renoofeettpenet t

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 56: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Theuserssettingsmayreduce

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 57: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

locationisdeterminedbytheavailablelocationproviders(netwrkandGS)thelocationpermissionsyourequestedandtheoptionsyousetinthelocationrequest

Torequestandstartlocationupd

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 58: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

3ODFHV$3

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 59: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

andlongitudebounds

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 60: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

TheMapsAPIdefinesasetofcustomXMLattributesforaMapFragmentoraMapViewobject

mapTypeSpecifythetypeofmaptodisplayValidvaluesincludenone

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 61: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

LFRQV3 2VLQFOXGHSDUNVVFKRROVJRYHUQPHQWEXLOGLQJVDQGPRUH

B usiness3 2V

UHREHVHQWEXVLQHVVHVVXFKDVVKRRFUHVWDXUDQWVRUKRWHOVKHQWKHPDSWSHLV

eth

EXVLQHVV3 2VDSSHDURQWKHPDSLQDGGLWLRQWRUHJHODU

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 62: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

[

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 63: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Target (location)

Thecameratargetisthelocationoftheceoerofthemapspecifiedaslatitudeaolooitude

Bearing (orientation)

Thecamerabearioisthedirectioniowhi averticallioonthemappoiosmeasuredioegreesclockwisefromorthSomeoodrivioacaroftenturoaroadmaptoalignitwith

theirMec

Tľptih tigw eieoo ala

d ohobei

d

i sep ellioon llfgnowhi avaiothemwisefro t a t ommmro hmbs ti

l e loob dmapoelsehecamerrosgnx ohashecamerae^asurediod

_miractolio ocamth

theirM them gnpo lon ᵐ

U G H JG H U H PE V X P H H H F D W L R Q

themi orM he llioo la

w dgwthh o ra o apf l tiBcal tif lcatiBo n )

roti

l e li on aeoo h

ection i o bear oaroao di gwthh f ctox qrioCcedilḸeuecadiao

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 64: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Thisisusefulifyouwanttoreplacethedefaultlevelpickerwithyourownlevelpickerforexampletocreateanaugmented-realityscavengerhuntinyourhome

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 65: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Stylingofthebase

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 66: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Note TheMy LocationlayerdoesnotreturnanydataToaccesslocat

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 67: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

TheAPIfirstcalls

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 68: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

YoucanusetransparenttileoverlaystoaddextrafeaturestothemapTomaketileoverlaystransparentsetatransparencyfactoronthetileoverlayprogrambrvbary

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 69: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Unlikewithamapitsnotpossibletoconfiguretheinitial theitheiepaipo te Ogravebmapntir i ni configuretheio te ioeue apia clc

osibfuinia l aoponftnitfui ne ooaig

uinoianfoitnioi l ao

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 70: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Related practicalTherelatedpracticaldocumentationisin91 t tni ncap et pp pnni Mr

9 d t

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 71: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Withcustomviewsyoucan

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 72: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

IfyouextendtheViewclassdrawthecustomviewsshapeandcontrolitsappearancebyoverridingViewmethodssuchasonDraw()andonMeasure()

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 73: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Adding the constructors

1 OpentheJavaclassyoucreated2

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 74: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ThecodeusessetCompoundDrawablesRelativeWithIntrinsic

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 75: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Thissectionshowshowtodrawthe

Acirc Iuml

נ

o

d

a

c

h

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 76: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

TheobtainStyledAttributes()methodreturnsaTypedArrayufuattributevaluesuincludingthefanOnColorandfanOffColorcustomat

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 77: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

7 K H F K D O O H Q J H L V W K D W R X K D Y H

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 78: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Thetypesofoperationsyoucanperformonacanvasinclude

Fil

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 79: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

MyCanvas

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 80: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Clipping amp O L S S L Q J isamethodfordefiningregionsofanimagecanvasorbitmapthatareselectivelydrawnornotdrawnontothescreenOnepurposeofclippingistoreduceoverdrawWhenyoureduceoverdrawyouminimizethenumberoftimesapixelorregionofthedisplayisdrawninordertomaximizedrawingperformanceYoucanalsouseclippingtocreateinterestingeffectsinuserinterfacede nandanimationn

Thefollowingscreenshotfromtheepplyingclippinetoacanvapracticalshowshowyon canclipandsombineclippineregions nyonshlisusomfollpsor pi r nCshli

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 81: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

121 AnimationsContents

W hat is animat ionTypes of animat ions f or AndroidV iew animat ionPropert y animat ionDrawable animat ionPhysics-based animat ionRelat ed pract icalsLearn more

What is animationAnimat ion is t he t echnique f or creat ing t he illusion of a moving object by showing a series ofdiscret e images t hat change over t ime such as

Af lip

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 82: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ThepropertyanimationsystemisarobustframeworkthatallowsyoutoanimatealmostanythingApropertyanimationchangesapropertysvalueoveraspecifiedlb gthoftimbForb( amplbyoucananimateacirclbtogrowbiggerbyincreasingi

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 83: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ATypeEvaluatorEvaluatorsmellmhemropertymnimationmystemmowmomalculatemaluesformmivenmropert

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 84: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

updatestheproperty

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 85: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Creating a physics-based animation

121Animations

247

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 86: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Theformatcanmeantheformatorencoding theindividualmediasamplesThisistencalledthe sample format codecanditdeterminesh themediasampleham c

ca codinthendileehmtThtillica iaiormatsodiahatľthenľľtThľte rmatsodiahatTccaiformahemeduaeiodit

iformahemodiaioe ldhformatcadmeantheformatcatheindielomiheca das

adielos

eeca

vidu eit

di medihamhca dahehdhamt tcזheeediaioT

tca eia thdmediehamatcaitdelos

eiah ca mhei ldthsh nľľnh

t saruha it dmed

l la madt

ditdc e

edmh h dאit

diasaruf

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 87: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

SeePlayamediafileontheCommonIntentspageformo

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 88: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

advancedtopicthatthiscoursedoesntexploreFormostdevelopersExoPlayerprovidesabetteroptionevenforcomplexmedia-playbackapps

ThecustomizabilityofExoPlayermakesitthepreferredchoiceformostmediaappsExoPlayersupportsmanyformatsandithasextensiblemodularf

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 89: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ThemediasourcefortheVideoViewisthelocationofthevideocontenttobeplayedThislocationisspecifiedbyaUriobjectrepresentingaUniformResourceIdentifierTheURIcanbe

ThelocationofavideofileembeddedinyourappasanAndroidresourceThelocationofafileavailableonexternalstoragesuchasanSDcardTheURLofamediafilelocatedonawebserverontheinternetAURIcontainedinadatabaseandsuppliedbyacontentprovideryoucreateAnyotherlocationthatcanbespecifiedbyaURI

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 90: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

ApreparationlistenerandtheonPrepared()callbackenableyoutoprovideinformationtotheuser(suchasaLoadingmessage)whilepreparationtakesplaceWhenthecallbackisinvokedtoindicatethatthemediaisreadytoplayyoucanremovethatmessageandplaythemedia

YoucandefineyourmedialistenersinonCrea () oranytimeyousetupyourmediaFor

o

w

usethese nPreparedL

ner()

methodwithaMed Pl rOnPreparedL

ner

objecttodefinetheonPrepared()callbackImplementthiscallbacktoaddcodetobeexecutedoncethemediahasbeenprepared

m

o

wse nPrepare

ner(newMed Pl rnPrepare

ner(

O r

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 91: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Ifyouwanttocreateamedia-playerappofanycomplexityonAndroidExoPlayeristherecommendedstartingplaceSeetheExoPlayerdeveloperguideorExoPlayerprojectformoreinformation

Architecture for complex media appsFormorecomplexmediaplayerappsincludingthosewhosemainpurposeistoplaymediaitisabestpracticetoensurethatyourappplayswellwiththeoverallAndroidplatformecosystemThispracticeisespeciallyimportantformusic-playerappsbecauseusersoftenexpectmusic-playerappstoplayevenwhentheappisnotvisibleonscreenandusersexpecttocontrolmusic-playerappsfromhardwaredevicessuchasheadsetbuttonsorthroughAndroidAuto

TointegratewiththeAndroidplatformtheAndroidmediaAPIsincludeanumberofclassestoabstractvariousaspectsofmediaplaybackbetmpnyourappandthesystemincludingmediasessionsmediacontrollersandmediabromersYouimplementtheseclassesinadditiontoandalongsideofyourappstransportcontrolsandmediaplayer

N te TheAndroidv4supportlibraryincludesC mpatversionsoftheclassesdescribedinthissectionintheMedia-C mpatsupportlibrary AswithallAndroidappsitisabest

thepldsetCcedilḸamer sesdescrid iastpractbrarh $s yspfroc-p mpanthe

tp pae

p

]h medismpanthe

tp pae

я dmmedis mpaAe AuAoid roi mpAuhlasse patricontrolsa o de

mpaAeAnhlasseo r seslaa

ec lss r ia

meAnhlasse m] eia rn

tpalongsi o] eacute

pnaolmuseacutebrar mayera edrpwaresor

Aswih dיaҵdrbromicontrols ofaҵ

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 92: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

YoucreateasinglemediasessionforyourappusuallyatthesametimeyoucreatethemediaplayerTheplayerisonlycalledfromthemediasessionthatcontrolsi

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 93: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Recommended Architecture ComponentsTointroducetheterminologyhereisashortintroductiontotheArchitectureCom

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 94: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Thedataforanappwithadatabasecentersa

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 95: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

todataacrossmultiplecomponentsofyourappcancreateexplicitr canatal

c

s alarc

em

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 96: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

UIcomponentsjustobserverelevantdataanddontstoporresumeobservationLiveDataisawareofvantda

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 97: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

W K H Q X S G D W H W K H F D F K H G G D W D I R U H [ D P S O H L Q W K H D G D S W H U D Q G W K H D G D S W H U X S G D W H V Z K D W W K H

X V H U V H H V

8 V X D O O R X R E V H U Y H G D W D L Q D ViewModelnotdirectlyintheR epositoryorinR oom

ViewModelisdescribedinalatersection

T hefollow ingcodeshow show toattachanobservertoLiveData

CreatetheobserverwhidupdatestheUI

finalObserverltStringgtnameObserver=newObserverltStringgt()

Override

publidvoidon anged(NullablefinalStringnewName)

UpdatetheUIinthitdseaTextView

mNameTextViewsetText(newName)

Modelge nurrentName()observe(thitnameObserver)

6 H H W K H LiveData

docum entationtolearno chbw aystouse

LiveDataorw a h cis

A rchitectureC om ponentsLiveD a andLifecycle ėideo

Room da baseRoom is a database layhb on top of a SQLi m a n

laec otem S

Rmter ees ce acutec ta

mtyhrver in R use2

s

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 98: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

7

R

X

VH

5R

R

P

ampUH

D

W

H

D

S

X

E

O

L

F

D

E

V

W

U

D

F

W

FODVVWK

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 99: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

thelifecyclelibraryForanintro$uctoryguidetothistopicseetheViewModel

overview

AViewModelhodsyourappsUIdatainalifecycle-consciouswaythatsurvivesconfigurationchangesSeparatingyo

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 100: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

deviceisrotatedIfyoustoreareferencetotheActivityintheViewModelyouendupwithreferencesthatpointtothedestroyed Activity hisisa e ory ea Ifyouneedthe

app icationconte tese

AndroidViewModel

instea of

ViewModel

IntheViewModel ese ive AdA

forchan ea edatathatthe Iwi eseordisp acothat

i oucana ano serveran respondtochan es ereistheco p etecode

per ic c Acc ordViewModel e dendc AndroidViewModel

privAde ordrepoc tor Mrepoc tor

privAde ive AdA ict ord MA ordc

per ic ordViewModel App icAdion App icAdion

ceper App icAdion

Mrepoc tor M new ordrepoc tor App icAdion

MA ordc M Mrepoc tor wed ordc

ive AdA icd ord wed ordc redern MA ordc

per ic void inc rd ord word Mrepoc tor inc rd word

IdadViewModel

isnotarep ace entfor

on Ave ncdAnc dAde ecaesethe ViewModeldoesnotservi e aprocesschetdown ee

avin Itatec

d o earn orewatchthisrchitectere o ponents iew odel video A rchitectere o ponents

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 101: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

mWordViewModelgetAllWords()observe(thisnewObserver

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 102: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:

Theandroidarchlifecyclepackageprovidesclassesandi

  • Table of Contents
  • Introduction
  • 11 Fragments
  • 12 Fragment lifecycle and communications
  • 21 App widgets
  • 31 Sensor basics
  • 32 Motion and position sensors
  • 40 Performance
  • 41 Rendering and layout
  • 42 Memory
  • 43 Best practices network battery compression
  • 51 Languages and layouts
  • 52 Locales
  • 61 Accessibility
  • 71 Location services
  • 81 Places API
  • 91 Google Maps API
  • 101 Custom views
  • 111 The Canvas class
  • 112 The SurfaceView class
  • 121 Animations
  • 131 Simple media playback
  • 141 Architecture Components
Page 103: Advanced Android Development Course – Concepts...Title Advanced Android Development Course – Concepts Author Google Developer Training Created Date 4/30/2018 6:36:49 PMFile Size:
  • 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