Location Use cases Best Practices

Location-based apps are absolutely everywhere like transportation apps, geo apps navigation apps, weather apps even dating apps all use location.We will dive into a common-use case that every developer has to address when they are writing location apps.we come up with some best practices. 

1.Use cached location

Use cached locationLet’s start with an obvious one, do you want to know the location of a device? For example, weather app, you want to show the right weather.You need to know, where the phone is?Here, I would say you don’t need location updates, you used cached location.Every time location is obtained from your device, it’s cached somewhere. You can use getLastLocation(). This will give you what you need in a lot of cases.The API has ways of knowing how stale or fresh this is.You save a tonne of battery that way.

2.User-visible(foreground) update

User visible updatesYou have user-visible foreground updates – for example, a mapping app of some kind.So here, because it is foreground, it is okay to use high accuracy, high frequency, and low latency.It’s expensive, but it is okay because, in the foreground, this is pretty much tied to your activities’ life cycle and it will end soon.So typically, what you would do in an activity is you would request location updates, but you would also do the following which is that onStop you remove the updates.Location gathering will keep happening long after your activities there, which is obviously a very, very bad thing to do.

3.Starting updated at a specific location

Starting updates at a specific locationAnother use case is you want to start location update at a specific location. You want to start location update when you’re near home, when you’re near work, near a cricket stadium-whatever. So here, it is a pretty good case of mixing geofencing and location updates.So, typically, what will happen is, imagine you’ve defined a geofence around some area of interest.If a user enters or exits a geofence, location services will let you know, and, at that point, you can say this is a trigger I was waiting for, I’m now going to request location updates.A common pattern for this is the geofence gets triggered, you get notified, you maybe show the user a notification, the user taps on notification, your app opens up to some activity, and, at that point, location updates begin.

4.Activity Recognition location update

Activity RecognitionAnother common use case is, where you want location updates but you only want them tied to a specific user activity – maybe when the user is riding a bike, or driving in a car.Here, we would use the activity-recognition API and combine that with location updates.It would work like the previous example: let’s say you were tracking cycling.Location services would tell you when the user is likely to be on a bicycle, and you can take that and start location updates to the notifications, something comes into the foreground.


5.Awareness API

Awareness APIAndroid has an exposed and an awareness API.It basically senses and infers your context, and it manages system health for you, and it does so in a battery-efficient manner. If you’re dealing with complex scenarios, awareness API may be exactly what you’re looking for.It tracks lots of things: what time of day is it? What is the location of the device? What are are the place nearby? Are there coffee shops or stadiums nearby?Houses of worship?What is the activity of the device, the person on a bike is the person on the car?Are there beacons nearby.It is a person wearing headphones.what is the weather like?You can take all of these contexts and treat of a larger sense of a fence.Basically, you can easily react to changes in multiple aspects of the user’s context and thing generalizes the idea of a fence well beyond conventional geofences which of course are just for the location.

So here is an example so, you create a context fence and it tracks three things you create an activity fence which says tracked that the user is driving it.Create a location fence and says track that this geofence may be a stadium geo being tracked. Then our time geo fence make sure it’s time between this time and this time when all of this thing are true you and your app is let’s say even in the background location services will say all the conditions you specified are true.I’m letting you know you can now do whatever and that whatever could include location update.

6.Snapshot API

Snapshot API that is made possible through awareness and again it’s a simple way to ask for multiple aspects of user’s context from a city again an example you find out what the current places, you find out what the current activity is? if the current place is a shopping mall and the activity is walking hey maybe it’s time to start location updates so that you can tell the user as walks what the stores are nearby or maybe some discounts that you can offer.

The thing is you are using multiple inputs and multiple contexts and that can get pretty expensive for battery because you’re running a lot of different things. If you use awareness API you can minimize battery cost because awareness API is actually pretty battery optimized.

7.Long-running(background) updates tied to specific locations

Long running updatesYou want to find all the Starbucks in the city or you want to find all the ATMs.Android has a solution that involves and a Dynamic geofence says location services make a requirement that you can only 100 geofences at one time there are of course many more ATM many more Starbucks than just a hundred and also maintaining 100 geofences is actually pretty expensive.That’s a lot of scanning that the location services will have to do and that’s going to drain your battery.So the solution is dynamic geofences maybe put a geofence around the city and when the device enters that city dynamically registered geofences in locations inside that city so you have the outer geofences dynamically you put energy offenses if the person leaves the city you can remove those dynamic geofences that are inside because you don’t need them anymore and this is a way you can actually in a very battery efficient way get a lot of geofences get around 100 geofences limit and actually do really pretty amazing things.

8.Long-running background updates.

The problematic one you want long-running background updates with no visible app component so basically think of an app that passively tracks your location for hours or days at a time. So this is a case that gives that keeps people up this the case that is inherently problematic and this is a case where you get into that problem. That I initially refer to that background location gathering is a really really major drain on battery but if you have to do it how do you it so?

Solution: long-running service?

Exposes a method for getting location updates using a PendingIntent and that’s exactly what you should do. So you request location updates you give it a location request you give it a PendingIntent and GMS core location services will wake up your app when an update is found.

In cases like this, what should location request look like what are you gonna do in the background that you gonna do in the background that doesn’t burn battery so you use moderate accuracy low frequency and high latency let’s just look at three of that thing right now.

You do not want accuracy which is priority high accuracy for any background use cases this bad for battery


For frequency, I think a good pattern would be to request updates times an hour let’s say every 15 minutes.Certainly, you should try to get more update through passive location gathering. So that’s why it’s a good idea to set the fastest interval to some small amount this way if others are gathering location you get that location for free doesn’t cost you anything.


Latency this is really really important again imagine that you set your interval to 15-minutes. If you set the max wait time to 1 hour you will get location updates every hour but you’ll updates which are calculated every 15 minutes at a time that’s pretty good for background and that will save battery.

9.Frequent Updates while a user interacts

Frequent updatesWhat if you want frequent updates while a user interacts with other apps?So imagine a Fitness app or Navigation app. So in this kind of a case, you should use a foreground service.This is sort of the recommendation that Android coming up with because android believes that when potentially expensive work is being done on behalf of the user that user should be aware of the work. A foreground service, as you know, requires a persistent notification.The user will be able to see


Related Posts

Creating and Monitoring Geofences

How Location API Works in Android

Understanding Battery Drain when using Location


Understanding Battery Drain when using Location

Turn off location

Users simply turn off location on their devices which means a lot of these apps either don’t work at all or they work in a degraded manner.

why do users do this?

Battery life huge problem

Because fairly or not, they associate a location with battery drain and they think turning off location will help preserve battery.Location is used a lot- we know that.

The relationship between Battery drain and Location

The relationship between battery drain and location in sort of a concrete way.I mentioned with the Fuse Location provider you have to essentially tell Fuse location provider what you want. You make a location request, and each does the right thing, and it does the right thing in a battery-efficient way.So, essentially, what this post is going to be, it’s going to about what is a good location request? How do you tell Fuse location provider what it should do? So, I would say battery can be measured on three points, the discussion can be anchored on this three-point: accuracy, frequency, latency.


It is course how accurate is your location? How fine do you want it to be? The way this works is that you can take the location request that you create and define a priority.There are a bunch of priorities that you can choose from, and depending on what you choose, the Fused location will give you different technologies under the hood and give you what you want.

The most accurate state-of-the-art is priority high accuracy.This will use GPS if it is available, and everyone will lose and accuracy will win.It is going to give you the most accurate location it knows how to do. This is a good kind of a use case for the foreground, when you have a short-lived activity that’s in the foreground, or something.This is a terrible idea for the background because it is going to be prohibitively expensive in terms of battery.

Related to that is another priority balance power accuracy.This will rarely use GPS but will have GPS matching and will not.I would recommend you writing the location apps to consider this something as a default.It does give you pretty good location without burning out your battery.

The next is “priority low power” and this will be hitting the cell network, not using a lot of Wi-Fi, it will not use GPS. This will give you coarse location.You can’t say I’m a few feet here or there, but you will be able to say I’m in this part of city vs that part of the city.Depending on your use case, this may be all you need in which case you should never request more expensive location updates than this.

The most interesting of all is the “priority no power”

Which is saying give you location updates but not spend any power.How does this bit of magic work? In this case, what you’re saying to Fused location power is don’t calculate any location for me.If another app is computing that, let me know the results.That’s what “priority now power” means and it’s an incredibly good tool to have because it doesn’t cost your app anything.


Again, it is fairly simple to understand what this means.The more frequent your updates, your location consumption, the more expensive.It is for the batter but it is a little bit more than that.Frequency is defined by a setIntervl().Location services will try to honor that value.If you say give me location updates every two minutes, it will try to do that.If you do it every 15 seconds, it will try to do that.Generally speaking, apps should pass the largest possible value when using setInterval().Especially background apps.Using intervals of a few seconds,15 seconds, 30 seconds, it really is something you should reserve for foreground use cases.Location services will sort of doing what you ask it does.It is up to you to choose wisely.Now, if you say location update setInterval() for two minutes, there’s caveat there which is that is just a suggestion.Your location updates may be a little slower or a little faster.The way that can happen a little faster is if another app is requesting location at a faster rate, that will be brought to your app as well because this location data is shared between apps.

So for that reason, Android has another method we can call in building our location request called setFastestInterval(..).It says give me the location, even if it is coming from another app no faster than what I’m specifying coming from another app no faster than what I’m specifying here.So, here’s a little example.

You create a location request object and set its interval to be five minutes.So at this point, every five minutes, your app is going to have location computed for it But if you also setFasterInterval(), which is, in this case, one minute, any app running out there this is requesting location also, that location will be made available to you but no faster than one minute.This is a pretty good way of not burning the battery yourself.You’re relying on other application to do the work and you get the location kind of freedom that they’re doing it is a passive way of getting location, and it’s a pretty powerful way of conserving battery.


The latency is really about when location services have a location to give you, how quickly do you need it? How quickly do you want location updates to be given to you?So, remember, we talked about setInterval(), when you set an interval of 30 seconds or two minutes, that’s what location services will try to use as this interval at which it gives you location.There also a method call setMaxWaitTime() which is a way of having your location delivered in watches after a few times after it’s been computed.setInterval() is how often is location computed for you? setMaxWaitTime() is how often location is delivered to you.

Let me make this concrete with an example.Again, we create a location request and set the interval to five minutes.This means low cakes will be computed for every five minutes.if in that time when the location is found and a new location is found, and your app will be woken up, and that location will be given to your app. If you set a max wait time of one hour, something different will happen.Your location will still be computed every 5 minutes but it will be delivered to you in a batch every hour, and you will get 12 location data points, at least in theory in. Instead of being woken up five minutes, your app will be woken up every hour which is dramatically better for battery consumption.Batching is a really, really good thing to use, especially for background case where you don’t want your device to get woken up a lot.

If you’re using geofencing, it’s the set Notification Responsiveness.if you don’t want your geofencing to be immediate, you can have a window to hold off before a geofencing result is given to your app. You can set the responsiveness period to something high, and that is also a very good thing for battery.

This is a classic case of how you build a geofence.you set a circular region, you set when it expires, you set what condition you want, and you build it.But if to that you add a setNotificationResponsiveness and give it a sufficiently large value.That will make your geofencing all the more battery-efficient.

That’s a bunch of stuff summarise, it is a fairly obvious thing, the more frequent and more accurate your updates and the lower your latency, the more expensive it is for battery. So, in foreground use case, you could have it all – you can be frequent, as accurate as you want, as low latency as you want, but for everything else,you’re going to have to trade off on one of these or more than one of these, and that’s where you get to preserve battery.


Related Posts

Creating and Monitoring Geofences

How Location API Works in Android

Location Use Cases Best Practices


How Location API Works in Android

Location-based apps are absolutely everywhere like transportation apps, geo apps navigation apps, weather apps even dating apps all use location.

Location APIs currently allow developers to request location at virtually anytime and make progressive location requests with no barriers.

Background location has major power issues

Background location has been identified as a major contributor to battery drain and power issues.Aggressive use of background location is a major reason why people disable location on their devices.So, in a response to this, the Android team starting with Android O put in place some fairly substantial limits on the gathering of background location.

What about pre O?

The majority are running on Android N or lower.What about those devices? For the foreseeable future, that is going to be the case.This talk is fundamentally about identifying best practices that you could use now in your Android apps when you use location. So that you’re writing your apps in a battery-efficient manner.Let’s dive into this.

Location APIs

Framework vs Fused location

For historical reasons, there are two ways in which you can get location when you’re using Android apps: Framework location and Fuse location.

android framework location apis

Framework location is the older one, been there the beginning.It is basically android.location.locationmanager giving you a wide API surface whereby you as app developers can decide I want to use GPS, I want to use wifi, with I want to use some sensor, and you can get the location as you see fit.This type of location is not optimized for battery, and we discourage you using this.what we would like to you instead is Fused location provider.This is available through GMS core.It is in android.gms.location.

Fused Location Provider

Fused location provider provides a narrower surface and sits on top of platform and hardware components.The way this work is you tell Fuse location provider what kind of location we want: forced, find, how frequently you want it.It just figures out what underlying technologies to use and how to do this in the most battery-efficient way.This location provider is highly optimized for battery, and we would like you to use this.

How Fused location Work?

There is a bunk of inputs that go into Fused location.There is Wi-Fi, GPS, Cell, Accelerometer, Gyroscope, Magnetometer.


GPS works great outside. It has some trouble with cities and tall building but in clear skies, it works fantastically, super accurate location but terrible for battery.That is your trade-off-great location accuracy but really bad for the battery.


The coverage for Wi-Fi is mostly indoors.The accuracy is pretty good.You can tell using just Wi-Fi where a person is in a building and what floor they’re on.The power consumption isn’t as bad as GPS but Wi-Fi scans are fairly expensive.It is not free: it does cost something.


This is available indoors and outdoors, available almost everywhere.The accuracy with the cell is not so great.You’re not going to get a location which is accurate to within a few feet, you will get the location to a neighborhood level or a city block, etcetera. But it is great for power consumption.It basically uses very, very little power, So it is fantastic for that.


Then you have the sensor which plays an extremely important role in making Fused location provider do the right thing and do the right thing for battery. You have an Accelerometer which measures changes in velocity and position. You have Gyroscope which measures changes in orientation in the device, and the Magnetometer which allows you to use the device as a compass.By and large, most of these sensors have very, very little battery cost.Fused location provider will use these sensors in conjunction with Wi-Fi and GPS to use the best as it can with minimal battery usage.

If you requested Fine location, accurate to within a few meters, Fuse location would use GPS and Wi-FI but GPS and Wi-Fi work better when you combine them with sensors.So, for instance, I mentioned GPS is a little bit jumpy when you’re in an environment with tall buildings.Imagine Hong Kong, Mumbai, New York City.Those are challenging environments for GPS. When GPS gets a little flaky, Fused location, instead of making expensive GPS scans, will say,”Let me see what the sensor data tell me.What is the accelerometer telling me?” It pieces together a pretty good sense of what is that is happening. The same with Wi-Fi, Wi-Fi can be a bit jumpy.When it gets jumpy, Fused location provider will not do excessive Wi-Fi scans but instead look at the sensor data and look at the what the device might be doing.Indoor maps sort of work like that.There was a time when Google maps would give you – if you want to a shopping mall, It would say you’re in this mall. Now it says you’re right here in this shopping mall on the third floor.It will do things like that.A lot of that is driven by sensors.If the location had to be pulled constantly, if the Wi-Fi scans had to be constantly done, that would be terrible for battery.It doesn’t have to do that.Once it gets a Wi-Fi fix, it can look to the sensor data and look in a battery-efficient way look where you are? you turning or moving, etcetera? That’s basically what it is. The Summary of this is, where possible, give the choice between framework location and Fused location, you should always use Fused location.


GeofencingThere’s one higher-level API that is the geofencing API, and that should be an important tool for anyone building location apps.It is a case where you can define a circular region somewhere and say whenever the device enters or leaves in the region, or sits in this region for a certain number of hours, do something.let me know and that basically is how geofencing works.Geofencing is built on top of Fused location and it’s highly optimized for battery. So the basically the way it works is the API monitors device proximity to a geofence.The closer you are to the geofence, the more expensive it is.It basically figures out what is your speed? Are you in the car? Are you walking? How far are you from the geofence. It optimizes for battery in terms of among Torrington the geofence in the background.

Related Posts

Creating and Monitoring Geofences

Understanding Battery drain when using Location

Location Use Cases Best Practices


Creating and Monitoring Geofences

What is Geofence?

Geofencing is a location-based service that sends a notification to smartphone users who enter a defined geographic area. Some companies send promotions to customers’ smartphones when they enter a store, mall or neighborhood.

geofence viewApplications of Geofence

Marketers can use geofencing by geofencing a retail store and send a coupon to a customer with a mobile app crosses the boundary.

Geofencing is used by the human resource department to monitor employees working in special locations

Geofencing, used with child location services, can notify parents if a child leaves a designated area.


To use geofencing, start by defining the geofences you want to monitor.Each Geofence object contains the following information:

  1. Latitude, longitude, and radius
  2. Expiration time
  3. Transition type
  4. Geofence ID

2.Set up for Geofence Monitoring

To use geofencing, your app must request ACCESS_FINE_LOCATION.To request this permission, add the following element as a child element of the <manifest> element in your app manifest

3.Set Up Google Play Service

Access the location provider, the project must include Google Play services. Download and install the Google Play services component via the SDK Manager and add the library to your project. For details, see the guide to Setting Up Google Play Services.

4.Connect to Google Play Services

To connect to the API, you need to create an instance of the Google Play services API client. In your activity’s onCreate() method, create an instance of Google API Client, using the GoogleApiClient.Builderclass to add the LocationServices API, as the following code snippet shows.

Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.

Here is an example activity that implements the callback interfaces that adds  to the Google API Client

To connect, call connect() from the activity’s onStart() method. To disconnect, call disconnect() from the activity’s onStop() method.

5.Request Location Updates

Before requesting location updates, your app must connect to location services and make a location request.Once a location request is in place you can start the regular updates by calling requestLocationUpdates().

Do this in the onConnected() callback provided by Google API Client, which is called when the client is ready.

Stop Location Updates

whether you want to stop the location updates when the activity is no longer in focus.

6.Create geofence objects

To create geofence object we need Latitude, Longitude, and Radius, Expiration time, Transition type, Geofence ID

Your app needs to create and add geofences using the location API’s builder class for creating Geofence objects, and the convenience class for adding them.

Specify geofences and initial triggers

The following snippet uses the GeofencingRequest class and its nested GeofencingRequestBuilder class to specify the geofences to monitor and to set how related geofence events are triggered

Geofence triggers

GEOFENCE_TRANSITION_ENTER:Transition triggers when a device enters a geofence GEOFENCE_TRANSITION_EXIT:Transition triggers when a device exits a geofence. INITIAL_TRIGGER_ENTER: Tells Location services that  should be triggered if the the device is already inside the geofence.                                                       INITIAL_TRIGGER_DWELL:Triggers events only when the user stops for a defined duration within a geofence. This approach can help reduce “alert spam” resulting from large numbers notifications.

7.Handle Geofence Transitions

When Location Services detects that the user has entered or exited a geofence, it sends out the Intent contained in the PendingIntent you included in the request to add geofences. This Intent is received by a Service which obtains the geofencing event from the intent, determines the type of Geofence transition(s), and determines which of the defined geofences was triggered. It then sends a notification as the output.

IntentService to listen for geofence transitions, add an element specifying the service name. This element must be a child of the <application> element:

The following snippet shows how to define an IntentService that log when a geofence transition occurs. You can define notification . When the user clicks the notification, the app’s main activity appears

Define an Intent for geofence transitions

The Intent sent from Location Services can trigger various actions in your app.IntentService is a good way to handle the intent. An IntentService can post a notification, do long-running background work, send intents to other services, or send a broadcast intent. The following snippet shows how to define a PendingIntent that starts an IntentService:

Add geofences

To add geofences, use the GeofencingApi.addGeofences() method. Provide the Google API client, the GeofencingRequest object, and the PendingIntent. The following snippet, which processes the results in onResult(),  implements ResultCallback:

Stop Geofence Monitoring

The following snippet removes geofences by PendingIntent, stopping all further notification when the device enters or exits previously added geofences:

When geofences required  Re-register?

The app must re-register geofences if they’re still needed after the following events, since the system cannot recover the geofences in the following cases:

  • The device is rebooted.
  • The app is uninstalled and re-installed.
  • The app’s data is cleared.
  • Google Play services data is cleared.
  • The app has received a GEOFENCE_NOT_AVAILABLE alert. This typically happens after NLP (Android’s Network Location Provider) is disabled.


Registered geofences are kept in the com.google.process.location process owned by the com.google.android.gms package. The app doesn’t need to do anything to handle the following events, because the system restores geofences after these events:

  • Google Play services is upgraded.
  • Google Play services is killed and restarted by the system due resource restriction.
  • The location process crashes.


Download this project from GitHub.

Related Posts

How Location API Works in Android

Understanding Battery drain when using Location

Location Use Cases Best Practices