7 - 3 - Location and Maps - Part 1 (13-53)

6
[BLANK_AUDIO] Hi, I'm Adam Porter, and this is Programming Mobile Applications for Android Handheld Systems. A few years ago my family spent some time in Montreal, Canada and right as we arrived it began to snow and snow and snow. And of course we, quickly found out that my two daughters had forgotten to pack their snow boots. So, we needed to buy boots and we needed to buy them from a store that was close to us. So I whipped out my mobile phone. And I ran a search for boots in the local area. The application came back with a list of shoe stores plotted on a map. The application also allowed me to get directions from my current location to the stores. We followed those directions, bought some boots and saved our vacation. Now I'm sure many of you could recount similar experiences. Sometimes the information we need depends critically on where we are at the time we need that information. To help out in these situations, Android includes support for location and maps. In today's lesson, I'll talk about some of the support. I'll talk about what location information is, and I'll go over the classes that your applications will use to get that information. I talk about maps, which allow you to take location information and display it visually to your users. And I'll finish up by going over the classes that Android provides, to let you display and customize map. So generally speaking, mobile applications can benefit from being location aware. That is no where bay, and other things are, at a partic, at a particular moment in time. And so Android allows applications to determine and manipulate location information. Now earlier I gave an example of using location capabilities, to find stores near my current location. And then to get directions from my current location to one of those stores.

Transcript of 7 - 3 - Location and Maps - Part 1 (13-53)

Page 1: 7 - 3 - Location and Maps - Part 1 (13-53)

[BLANK_AUDIO]Hi, I'm Adam Porter, and this isProgramming Mobile Applications forAndroid Handheld Systems.A few years ago my family spent some timein Montreal, Canadaand right as we arrived it began to snowand snow and snow.And of course we, quickly found out thatmytwo daughters had forgotten to pack theirsnow boots.So, we needed to buy boots and we neededtobuy them from a store that was close tous.So I whipped out my mobile phone.And I ran a search for boots in the localarea.The application came back with a list ofshoe stores plotted on a map.The application also allowed me to getdirections from my current location to thestores.We followed those directions, bought someboots and saved our vacation.Now I'm sure many of you could recountsimilar experiences.Sometimes the information we need dependscritically on wherewe are at the time we need thatinformation.To help out in these situations, Androidincludes support for location and maps.In today's lesson,I'll talk about some of the support.I'll talk about what location informationis, and I'll go overthe classes that your applications willuse to get that information.I talk about maps, which allow you to takelocation information and display itvisually to your users.And I'll finish up by going over theclasses that Android provides,to let you display and customize map.So generally speaking, mobile applicationscan benefit from being location aware.That is no where bay, and other thingsare,at a partic, at a particular moment intime.And so Android allows applicationsto determine and manipulate locationinformation.Now earlier I gave an exampleof using location capabilities, to findstores near my current location.And then to get directions from my currentlocation to one of those stores.

Page 2: 7 - 3 - Location and Maps - Part 1 (13-53)

In addition, applications can also usethis capability todo things like define a geographical areaor geofence.And then to initiate actions when the userenters.Or exits the Geofence.Android provides several support classesto make all of this possible.One of our classes is the location class.A location represents a position on theEarth.A location instance contains informationsuch aslatitude, longitude, a time stamp andoptionallyan estimated accuracy, altitude, speed andbearing.Location information comes from locationproviders anddevices can have access to multiplelocation providers.Now the actual data may come from sourcessuchas GPS satellites, cell phone towers andWiFi access points.Specifically, applications can requestinformation from the networkprovider, the GPS provider and passiveprovider.Let's look at each of these, one at atime.The network provider, determines locationbased on cell tower andWiFi access points.If you want to use this provider,then you must declare either theACCESS_COARSE_LOCATIONpermission.Or the ACCESS_FINE_LOCATIONpermission.GPS provider gets its location permissionfrom GPS satellites.To use this provider, you must declare theACCESS_FINE_LOCATION permission.The passive provider doesn't actually turnon any devices.It just returns locations that happen tohavebeen calculated through the requests ofother applications.So using this provider requiresthat you declare the ACCESS_FINE_LOCATIONpermission.Now while you can get location informationfrom each of these different sources,each one offers a different set of tradeoffs with respect to cost.Accuracy, availability, and timeliness ofthe data it provides.

Page 3: 7 - 3 - Location and Maps - Part 1 (13-53)

Let's look at some of the providers,available in Android.The GPS provider relies on communicatingwith a satellite.And so, this provider is generally themost expensive but gives the most accuratereadings.It also takes the longest amount of timeto provide that very accurate reading, andtheuser needs to have a clear view ofthe sky when they're communicating withthe GPS satellite.The network provider is cheaper than theGPS provider.But, it may give less accurate readings.It takes less time to return locationinformation, but it's only usefulwhen you're in the range of a cell toweror WiFi access point.The passive provider is the cheapest touse.You're essentially just reusingmeasurements that already have been taken.So it's fast,but it may turn out that there are norecent readings when your application asksfor that information.One way to access location information isto use the location manager class.The location manager is a system servicefor accessing location data.You acquire a reference to the locationmanager by calling the contextclasses get system service method, passingin an ID for the service.Context.LOCATION_SERVICE.Once you have a referenceto the location manager, you can use it toget and use location information.For instance, you can determine the lastreading taken by a particular provider.You can register for location updates tofind out when new location information isacquired.And you can also register to receiveintents.When the device nears or moves away from agiven geographic region.If you want to be informed when newlocationsare determined, you can implement and usea location listener.The location listener interface definesthe callbackmethods that are called when locationchanges.Or, when the status ofa location provider changes.A location listener interface includes the

Page 4: 7 - 3 - Location and Maps - Part 1 (13-53)

following methods.On location changed.Which gets called when a new location wasdetermined.onProviderDisabled and onProviderEnabled,which are called whenthe user disables or enables a particularprovider.And onStatusChanged,which is called when a provider's statuschanges.If your application can't get a recentreading from thesystem, it will then need to acquire itsown reading.And to do this, your application willnormally perform the following steps.First, it will start listening for updatesfrom location providers by registering alocation listener.Next, it should maintain and update acurrent best estimate,as it begins to receive location updates.And as this process unfolds,the application should determine when thecurrent best estimate is good enough.And at that point it should stop listeningfor location updates by unregistering thelocation listener.And finally, it can use that best estimateas the current location.Now when you're determining whether yourlocation is goodenough, there are several factors that youmight want to consider.For example, for how long should you keepmeasuring?For instance, a navigation system mightneed continuous measurement.While a restaurant finder applicationmight just need a single measurement.Another question is, how accuratea measurement do you actually need?And again, a navigation system needs toknowyour location to say, within ten meters orso.A restaurant application, might just needto know what city you're in.And in that case, you'd only need to know,you'relocation to say, within a kilometer, ormaybe even less.And of course, the choices you make here,clearly impact,battery usage.The example application is called,location, get location.This application, first acquires anddisplays, a, the last known location, from

Page 5: 7 - 3 - Location and Maps - Part 1 (13-53)

all the providers on the device.If these readings are too old, or have toolow accuracy.Then the application acquires and displaysnew readingsfrom all the providers on the device.Let's give the application a run.So here's my device.Now, I'll start the location GetLocationapplication.When the application starts up, itdisplaysthe best previous location estimate fromthe device.This information is then displayed usingred text.Since this reading is either not recentenoughor doesn't have enough accuracy, theapplication goes onto acquire new location estimates, and youcan seethat these new readings are displayedusing grey text.Let's look at the source code for thisapplication.So here's the application open in the IDE,now I'll open up the main activity.And let's scroll down to the on createmethod.And here we see that the code acquires areference to the location manager.Next, it calls a method called best lastknown location.This methodwill find the last known location fromevery location provider, and thenwill return the most accurate ofthese measurements that also meets certaincriteria.If no readings meets those criteria, andthe method returns null.Next, the code displays information aboutthe last reading.After this, the codecontinues by defining a location listener.And in the listener's on location changemethod, the code determineswhether the new location is better thanthe current best estimate.If so, the code then updates the bestestimate, and then updates the display.Now, if the accuracy is less thanmin_accuracy,then the current location is consideredgood enough.And so the code unregisters the locationlistener.Now, scrolling down, you see the on resumemethod.

Page 6: 7 - 3 - Location and Maps - Part 1 (13-53)

This method checks to see whether thecurrent best estimate, isof low accuracy, or was taken more thantwo minutes ago.If so, the code registers listeners forboththe network provider, and for the GPSprovider.After that, the code schedules a runnable,that will unregister the listeners aftera fixed period of time.The code will also unregister the locationlistener, if the activity's onPause methodis called.[BLANK_AUDIO]Here are some tips you can use tosave battery power when you're creatinglocation aware applications.First, always check the last knownmeasurement.If that's good enough, then there's noneed to take new measurements.Return updates as infrequently as possibleand limit the total measurement time.Some applications, such as an applicationthat tracks a jogger.Need to update more frequently and need tokeep measuringwhile the application is running becausethe user's location is changing.Applications like the one we just sawthough will need asingle good measurement so they canmeasure infrequently and for less time.Use the least accurate measurementnecessary, andonly use GPS if you really need too.Turn off the updates in OnPause.[BLANK_AUDIO]