To support backward compatibility, if your application doesn't target Q then the ACCESS_BACKGROUND_LOCATION permission will be added if the COARSE or FINE ...
GetunlimitedaccessOpeninappHomeNotificationsListsStoriesWritePublishedinGoogleDevelopersExpertsExploringAndroidQ:LocationPermissionsThisarticlewasoriginallypostedonhttps://joebirch.co/LastweekwesawtheannouncementoftheAndroidQbetareleaseWiththisversionofAndroidcomesacollectionofexcitingchangeswhichweneedtogetourappsreadyfor.InthissetofarticlesI’mgoingtobedivingintoeachoneofthesesothatwearefullypreparedforgettingourappsready!Note:Youcanfindthecodeforthisarticlehere.AsoutlinedinthebetareleasenotesforAndroidQ,oneofthechangesweareseeingintroducedisthewayinwhichweworkwithuserlocationsinsideofourapplications—thesechangesaffecttheaccessofthelocationinboththeforegroundandbackground.Thisgivesourusersmorecontrolofwhentheywishappstobeabletoaccesstheirlocation—allowingthemtorestrictingittoonlywhentheappiscurrentlyinuse.InthispostIwanttotakeaquickdiveintohowthesechangeswilleffectapps,alongwithwhatweneedtodotoadapttothesechanges.ForegroundLocationPermissionTheremaybecaseswhereanapplicationrequiresaccesstotheuserslocationwhilstthereisacontinuationofuser-initiatedactions.Forexample,maybeyourappdeliversnavigationtotheuser—oncetheusernavigatestotheirhomescreenfromyourapp,you’llwanttocontinuehavingaccesstotheirlocationin-ordertocontinueservingnavigationtothem.Ifyou’reutilisingaforegroundservicetohandlethisfunctionalitythenwe’llonlyneedforegroundaccesstotheuserslocation,asthere’snoreasonforustoaccesstheuserslocationfromthebackground(we’llcoverthecasewherewemaynotbeusingaforegroundserviceinthenextsection.).Whenyourapplicationrequiresaccesstothislocationdata,it’simportanttoletyouruserknowwhywhenaccessingit.Tobeginwith,anyserviceofthiskindthatmakesuseoftheuserslocationneedstobedeclaredasalocationforegroundservice.ThiscanbedonebymakinguseoftheforegroundServiceTypewhendeclaringyourservicewithinyourmanifestfile.Beforewetrytokickoffourforegroundserviceweneedtoensurethatwehavetherequiredpermissionfromtheusertodoso.WecandothisbycheckingfortheACCESS_COARSE_LOCATIONpermission.Now,thisisn’tanewpermission—infact,it’sbeenaroundsinceAPIlevel1.However,weonlypreviouslyneededtodefinewithinourapplicationmanifestfile—nowwemustrequestthispermissionatruntime.Youcanseehowthisnowgivesourusermuchmorecontroloverhowthispermissionisused.valhasLocationPermission=ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTEDif(hasLocationPermission){//handlelocationupdate}else{ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),REQUEST_CODE_FOREGROUND)}Inthiscodeaboveyoucanseethatwebeginbycheckingwhetherwehavethelocationpermission.Ifso,wecancontinuetohandlethelocationfloworotherwise,wemustrequestthepermissionfromtheuser.Ifthisisthecase,thenwewillreceivethepermissionstatewithintheonRequestPermissionsResult()callbackwithinourcallingclass.Whenwerequestthispermission,ouruserwillbedisplayedthefollowingdialog:Asyoucansee,theintentofthepermissionhasbeenmadequiteclear—ourappwillonlyhaveaccesstotheirlocationwhilstintheforeground(asin,theappisbeingused).Iftheuserhasdeniedthispermissionatanypointandwerequestitagain,thentheywillbeshownaslightvariationofthedialog:Similartohowtheruntimepermissionsinandroidusuallywork,weknowareshownanoptionwheretheusercanrequestnottobeaskedagain.Becauseofthisfunctionality,it’simportantthatyouonlyaskforthisforegroundlocationaccessatthepointitisrequired.Thisguidesyouruserastowhythepermissionisrequiredinthecurrentcontext,ratherthangivethefeelingthatitisbeingaskedfornoreason.BackgroundlocationpermissionWhenitcomestoaccessingtheuserlocationwhenourappisbackgrounded,thingsworkalittlebitdifferently.Wefirstneedtoaddanewpermissiontoourmanifestfile,thisistheACCESS_BACKGROUND_LOCATIONpermission.Althoughthisisdeclaredinthemanifest,itcanstillberevokedatanytimebytheuser.Notethatherewearen’trequiredtoaddtheforegroundServiceTypeservicetypetoourservicedeclaration,thisisbecausewedon’tneedmomentarypermissiontorunoutsideofourapp—thisbackgroundpermissionalreadygivesourapplicationtheabilitytodothis.Aswellastheabove,thepermissionneedstobegrantedbytheuseratruntime.Sobeforewetryandaccesstheuserslocationfromthebackground,weneedtoensurethatwehavetherequiredpermissionfromtheusertodoso.WecandothisbycheckingfortheACCESS_BACKGROUND_LOCATIONpermission.Youcanseeagainhowthisnowgivesourusermuchmorecontroloverhowthispermissionisusedandavoidsbackgroundlocationaccessbeingabused.Ourcodeforcheckingthepermissionmaylooksomethinglikethis:valhasForegroundLocationPermission=ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTEDif(hasForegroundLocationPermission){valhasBackgroundLocationPermission=ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_BACKGROUND_LOCATION)==PackageManager.PERMISSION_GRANTEDif(hasBackgroundLocationPermission){//handlelocationupdate}else{ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),REQUEST_CODE_BACKGROUND)}}else{ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION),REQUEST_CODE_BACKGROUND)}You’llnoticethatthiscodeisprettysimilartothechecksthatwedefinedfortheforegroundlocationpermission.Herewecheckforbothpermissions,givingusafallbackinlocationretrievalshouldtheuserdenyusbackgroundaccessforsomereason.Whenwerequestthispermission,ouruserwillbedisplayedthefollowingdialog:Theintentofthepermissionhasbeenmadequiteclear—ourappwillbeabletoaccesstheirlocationwhilstinthebackground.Iftheuserhasdeniedthispermissionatanypointandwerequestitagain,thentheywillbeshownaslightvariationofthedialog:Similartohowtheruntimepermissionsinandroidusuallywork,weknowareshownanoptionwheretheusercanrequestnottobeaskedagain.Becauseofthisfunctionality,it’simportantthatyouonlyaskforthisbackgroundlocationaccessatthepointitisrequired.Thisguidesyouruserastowhythepermissionisrequiredinthecurrentcontext,ratherthangivethefeelingthatitisbeingaskedfornoreason.WecanseefromthisarticlethatAndroidQchangesthewayinwhichourapplicationsworkswithlocationpermissions.Ourappswillnolongerbeabletofreelyaccesstheuserlocationsfromservices,whetherintheforegroundorbackground.Tosupportbackwardcompatibility,ifyourapplicationdoesn’ttargetQthentheACCESS_BACKGROUND_LOCATIONpermissionwillbeaddediftheCOARSEorFINEpermissionsaredeclared.Similarly,requestingeitherofthetwoatruntimewillalsograntthepermission.Thesechangesgiveourusersmorecontroloverhowapplicationsaccesstheirlocation,allowingustocreateappswiththeusersprivacyandsafetyinmind.Anyquestionsabouttheselocationchanges?Feelfreetoreachoutinthecomments!JoeBirch(@hitherejoe)|TwitterThelatestTweetsfromJoeBirch(@hitherejoe)[email protected]@Android,@GooglePay&…twitter.comMorefromGoogleDevelopersExpertsExpertsonvariousGoogleproductstalkingtech.ReadmorefromGoogleDevelopersExpertsRecommendedfromMediumDavisZhangD-BI|DavisonBIAdrienneDomingusDjango:AtScaleinProductionJimLaiWhyRxSwiftmayNOTbethesolutionyouarelookingfor.ChanakKarkiIntothedata:Day32CasperDefiGoodnewsguys🎉GuilhermeRPereiraTelemetrywithOpenTelemetry,PrometheusandJaegerManelC.inCircuitSlimesDevlogDevlog — Week3BeekeyCheungRandomnessinSoftwareEstimatesAboutHelpTermsPrivacyGettheMediumappGetstartedJoeBirch15.7KFollowersAndroidEngineeringLeadatBuffer,GoogleDeveloperExpertforAndroid&Flutter-Passionateaboutmobiledevelopmentandlearning.www.joebirch.coFollowHelpStatusWritersBlogCareersPrivacyTermsAboutKnowable