Getting user location with minimal impact for battery on Android - android

I'm starting to develop an app that will stay in background forever and detect when a user is staying in a certain location for a while (and then display a notification to invite the user to open the app to obtain informations about that place).
It's something very similar to what Google Maps does when you're in a restaurant and it shows you a notification to check ratings about it.
What I want is to have a minimal impact on device, so location updates should be very "passive", getting the location only when user is not moving and, if possible, recycling location data that is already got by other activities - maybe by Google Maps itself or other location apps that are running on the devices.
This is not a navigation app, so I don't need to have the live fine location but simply the approximate place with the best accuracy and minimal effort, and only if user is not moving.
LocationListener and onLocationChanged seems to be my men, but can I specify that I don't want to trigger device's sensors and only re-use location data when it's available for other scopes? My app should check these informations and then decide to do a reverse geocode if and when they are accurate enough.

Yes, LocationListener and onLocationChanged are your men, though for a passive implementation, there are a few options you can go through.
First you can check for the last known location, maybe compare it in terms of its time; i.e. getTime() and verify whether it is of use to you.
In terms of code, literally...
Google samples, android location has what is relevant for the last location part:
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Provides a simple way of getting a device's location and is well suited for
// applications that do not require a fine-grained location and that do not need location
// updates. Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Further, you can combine it with LocationRequest object, this helps your implementation as you can call it right after trying getLastLocation() and basically have a more reliable arrangement for obtaining location.
// Create the location request
mLocationRequest = LocationRequest.create()
//priority object needs to be set, the following will definitely get results for you
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
//interval updates can be on the lines of 15mins or 30... acc to your requirement
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
i suggest give PRIORITY_NO_POWER a try, could work well in combination with getLastLocation(). These power modes have been added specifically for optimising battery/power consumption and efficiency for retrieving location.

Related

Android fused location api not providing consistent updates with screen off

I have some code that runs multiple times per second in my app. I'm trying to get my location in every cycle. I am using the following:
Location myLastPos = LocationServices.FusedLocationApi.getLastLocation(googleApiClient)
My app also runs in the background using a PARTIAL_WAKE_LOCK. With the screen on everything seems OK. When I turn the screen off my app still runs normally but I no longer get location updates consistently.
It appears that I get updates much less frequently (often minutes in between updates). I'm checking the timestamp of the location using:
myLastPos.getElapsedRealtimeNanos()
I also found that even when the screen is on I get some strange results. Sometimes I get a few milliseconds between updates, other times I get a few seconds. This is all very concerning. Can someone either help me use FusedLocationApi properly or suggest an alternative. All I really want is to poll the gps directly for lat/long a few times a second without google libraries getting in the way.
The getLastLocation() method just gets the last known location that the device happens to know. The "last known location" here means exactly that: It may not be up-to-date. Locations do come with a time stamp which could be used to asses if the location might still be relevant.
The device doesn't determine its location on its own, but only when some application request the location. So your app is now dependent on other applications requesting location updates.
If you need updates every few seconds, then request regular location updates yourself.
Android documentation recommends the FusedLocationProvider, but the LocationManager is also a perfectly valid option, if there's any reason to avoid the Google Play services.
The basic idea is to first request location updates:
// Using LocationManager as an example.
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Using GPS, requesting location updates as soon as available and even for
// the smallest changes. Here 'this' refers to our LocationListener
// implementation.
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
The updates are then received by a listener:
#Override
public void onLocationChanged(Location location) {
// We received a location update.
// Copy the value from the method parameter to our
// class member variable.
mLocation = location;
}
And when you no longer need the updates you should cancel the request:
mLocationManager.removeUpdates(this);
The approach is very similar for the FusedLocationProvider.

google play services location api sometimes give wrong location

My app use Google Play service API to get the user location and check if the device is inside or outside a particular area of 50 mt of radius.
The app use PRIORITY_HIGH_ACCURACY and a Interval of 1 minute.
So I create GoogleApiClient:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
In the onConnected callback:
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(60000);
mLocationRequest.setFastestInterval(10000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
and
MyLocationListener.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
My app also filter locations based on accuracy (if accuracy > 200 mt I discard it) and time (if it is too old I discard it).
The app works fine except in some particular areas where sometimes it returns wrong locations update about 500 meters from the real location, and those wrong locations are always near the same place, some step away from a Cell Tower.
In those areas I get a combination of wrong and correct locations and my app think that the device is sometimes inside and sometimes outside the area of interest.
When I get a location update I wait for other 3 in a row to confirm the position. Also I filter location if exactly the same as the previous. This means that when I m getting those errors I'm receiving 4 wrong locations in a row each one slightly different from the others.
Is there a way to prevent this behavior? Can this be caused by the Cell Tower?
There's always a chance of it being wrong. An accuracy of 200m doesn't mean its within 200m- it means there's a 67% chance you're within 200m. There's still a 1/3 chance you aren't.
Since most of the Google Play location providers are fused (use GPS and wifi/cell data), yes being very close to a tower could screw with the data.
Change setInterval(60000) to setInterval(20000) or to 5000.
Since the interval is one minute, you won't get updates even if the user moves. That's why there is an inaccuracy.
According to Google, setInterval(long) means - set the interval in which you want to get locations. setFastestInterval(long) means - if a location is available sooner you can get it (i.e. another app is using the location services. Means, if no other apps are using the location service, you will get updates only after a minute).

android location update frequency

I want to get 5 consecutive update locations in order to check if the user is moving and to make sure the GPS is calibrated. I did the following:
I added android.permission.ACCESS_FINE_LOCATION" to the manifest and in onConnected:
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
mLocationRequest.setFastestInterval(1000);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
and in onLocationChanged I did the following:
locationRetries++;
switch (locationRetries) {
case 1: {
firstLatitude = location.getLatitude();
firstLongitude = location.getLongitude();
}
case 5: {
locationRetries = 0;
lastLatitude = location.getLatitude();
lastLongitude = location.getLongitude();
accuracy = Math.round(location.getAccuracy());
stopLocationUpdates();//will remove from location updates and disconnects
float[] results = new float[1];
Location.distanceBetween(firstLatitude, firstLongitude, lastLatitude, lastLongitude, results);
if (results[0] > 5)... //if moved at least 5meters, show popup that the user is moving else do your thing
}
Now I have 3 issues:
1) It seems to take much less than 5 seconds to retrieve the 5 updates even though I set both parameters to be 1000 milliseconds.
2) All the 5 locations (at least the first and last ones) are the same exact location even though I was walking fast. I thought I maybe moving too slow so
3) I closed my app, reopened it on a far location and pressed the button. Almost instantly I got the previous location. I pressed the button again and then I got the real location I was on. It's as if it didn't really asked/waited for a location from the GPS but instead took the last one which was remotely inaccurate at the time. I don't have any "get last known location" code.
I guess the bottom line would be: how can I make sure that it really asks the GPS where am I when I asked for the location and also when asking it for 5 consecutive times, to give me the real locations and not from the cache(?).
The Fused Location Provider
intelligently manages the underlying location technology and gives you the best location according to your needs.
Simple APIs: Lets you specify high-level needs like "high accuracy" or "low power", instead of having to worry about location providers.
Immediately available: Gives your apps immediate access to the best, most recent location.
Power-efficiency: Minimizes your app's use of power. Based on all incoming location requests and available sensors, fused location provider chooses the most efficient way to meet those needs.
Versatility: Meets a wide range of needs, from foreground uses that need highly accurate location to background uses that need periodic location updates with negligible power impact.
There is no guarantee that the fused location provider will ever use GPS - if it has a recent location of the accuracy you request it will return until a better location is returned (i.e., live GPS is returning accurate locations). This ensures that you'll get a better location sooner without waiting for GPS to be primed.
If you specifically need data from GPS, you need to use the LocationManager using the GPS_PROVIDER.
If you are trying to determine what the user is currently doing, you can instead use the ActivityRecognitionApi, which returns DetectedActivity such as WALKING or STILL: using that would give a faster method to understand what the user is currently doing.

Android Location Update Clarification

Am working with the location update application which will update the user location periodically to the server.
I have used the fused location provider to get the location update. I have referred the following link Android Location Update.
Regarding the location update I have following clarifications,
1) I requested Location using Pending Intent. I had given the Time
interval as 5 min in the location request. I am getting the location
information successfully at every 5 min. But my question is "How effectively
Android uses the GPS to get the location - GPS need not to be on for
the whole 5 min". Around 4 min 50 seconds it starts using the GPS to
get the user location. I just want to know how the fused location provider effectively using the GPS.
2) And also I want to know the time taken to fetch the user location
by using available providers. How much time approximately taken by the
android api to get the user location by using fusion location
provider.
3) The Fused Location Provider uses GPS only at the nearest time of given interval to get
the user location. The remaining time the GPS is not usable. Is there
is better solution to switch off the GPs or effective way to use the
GPS to save the mobile battery power.
4) Am giving the time interval as 1 min. Some time am not getting the
location update every one minute. For Example, First minute successfully
I am getting the user location. Then not getting the user location at 2nd Minute. Then 3rd minute
getting fine and so. I have GPS ON and with mobile network available and WiFi
connected.
5) And what is the maximum time interval we can give. Am not finding
any maximum time limit in the document. We can give the minimum time interval as zero. But it is not recommended.
6) And also I want to know the minimum OS support while using this feature. I have referred below link Does Google Activity Recognition work on older versions of Android? Which says Everything in Google Play Services should work back to API level 8(Android 2.3).
Please help me on this. I hope this could help other developer also who are working on Android Location Updates.
Thanks in advance.
I have used the fused location provider API's in our project and it's was really helpful to improve battery usage.Earlier We were using Android's Location framework APi's .
Please read below article which I have prepared ,you can refer the information to implement it in your project.
In simple words, it’s the best way to get location data in Android platform as of now.
GooglePlay Services provide many location APi’s to get the location data(e.g. User’s current location or you can say device’s last known location).
The Fused Location Provider is one of the location APIs in Google Play services.
Prerequisite is that:
1- Google Play services sdk is used as library project(and also Google PlayService is properly installed in your device)
Download and install the Google Play services component from the SDK Manager and add the library to your project.
Import GooglePlayServices lib from android google-play-services_lib in your development project as Library project.
2- You should have an actual device as this APi won’t work in Emulator.
The Fused Location Provider intelligently manages the underlying location technology (GPS/Wi-Fi/Network provider’s connection) and gives us the best location according to our needs.
Why to use
=============
We could choose one of the location providers (network or GPS) and request location updates or set up proximity alert. But there were two main issues with this approach:
1. In case we need to define precise location, we had to switch between network and GPS location providers (as GPS doesn’t work indoors).
2. Proximity alerts were used to notify a user about proximity to a location, and this took its toll on the battery life.
Benefits
==========
1. Simple APIs: Lets us specify high-level needs like “high accuracy” or “low power”, instead of having to worry about location providers.
2. Battery efficient: Minimizes out app’s use of power. Based on all incoming location requests and available sensors, fused location provider chooses the most efficient way to meet those needs.
Steps to use this Api:
=====================
1- Declare the location related permission in the manifest file.
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>
Or
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
2. Implement related interfaces and callbacks.
Before we request location updates, we must first implement the interfaces that Location Services uses to communicate connection status to our app:
2.1 com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks: Specifies methods that Location Services calls when a location client is connected or disconnected.
2.2
com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener
3 Connect to Google Play Services
Connecting LocationClient to Google api.To do this , create a LocationClient object (it’s actually instance of GoogleApiClient object) as below:
mLocationClient = new GoogleApiClient.Builder(getApplicationContext())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
and then call connect() :
mLocationClient.connect();
4- Create an instance of FusedLocationProviderApi by using LocationServices class as below:
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
5- Retrieve the current location
Inside onConnected(Bundle bundle){
Location currentLocation = fusedLocationProviderApi .getLastLocation(mLocationClient);
if (mCurrentLocation != null) {
Log.d(TAG, "last location =" + mCurrentLocation.getLatitude()
+ " - " + mCurrentLocation.getLongitude());
}
}
6- Receive periodic location updates
Create and setup LocationRequest object:
mLocationRequest = new LocationRequest();
private void setLocationParameter() {
// Set the update interval
mLocationRequest.setInterval(Constants.SECONDS_TO_UP);
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest.setFastestInterval(Constants.SECONDS_TO_UP);
// Set the distance to 10 meters.
mLocationRequest.setSmallestDisplacement(Constants.METERS_TO_UP);
}
6- Request for periodic Location updates: To get periodic location updates from Location Services, we send a request using a location client.
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Utils.locationUpdates = Utils.locationUpdates + 1;
if (Utils.locationUpdates == 1) {
mLocationRequest
.setPriority(LocationRequest.PRIORITY_LOW_POWER);
LocationServices.FusedLocationApi.requestLocationUpdates(
mLocationClient, mLocationRequest, listener);
}
}
}
};

Android Location Client not as Accurate as Google Maps App

I want to preface this by saying that I'm in China where Google location services sometimes have issues.
I'm using the LocationClient to get user's current location.
protected void onCreate(Bundle savedInstanceState) {
...
mLocationClient = new LocationClient(this, this, this);
...
}
Very straightforward. Then in my onConnected callback, I get the location.
public void onConnected(Bundle connectionHint) {
Location location = mLocationClient.getLastLocation();
...
}
The location I get back is always the same, but it is about ~500m away from my actual location. GPS is enabled, although the icon indicating it is being used does not come on. I am also on WiFi and have 3G.
When I open the actual Google Maps app, my location is perfectly accurate (unlike the location I get in my own app). I also see the icon indicating GPS is being used.
Questions
What is the Google Map app doing differently to get a more accurate location and how do I do what they do?
If the wrong location I get back is always the same what does that mean? Without overthinking too much, it is a truth of China that foreign map data companies have coordinates the are skewed off by a factor and they have to use a specific algorithm to correct for that difference; is the Google Maps app doing that?
Thanks!
When using the method 'getLastLocation()', it offers the best last known location stored by the Location. It is also in respect to what level of permission you have given the app in the manifest file.
Try using both:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
in your manifest file and see if it improves the accuracy.
China has a special dealing with GPS data, because the government force the related map producing company to add some bias.
I'm stuck with it for a period of time.
Ad. 1 Google Maps updates location continually. Try following these inductions: http://developer.android.com/training/location/receive-location-updates.html
Ad. 2 getLastLocation probably retrieves last location stored when it is updated like in point 1. If it's not updated, you will just get the same value. Location object has time attached and you can see when it was received.
turn on the Satellite view. The normal "vector" view is obfuscated in China. For some reason, the Google Maps app doesn't have this issue.
the location returned by the GPS is correct, even in China (considering a WGS84 projection). Only the maps are not.
Other maps providers like Baidu force you to use their own custom implementation of LocationClient. This way you get locations ready to be used on their map tiles.
A late answer, but this hasn't been said:
You can set the accuracy of the locationClient, using the locationRequest.
E.g.
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(mLocationRequest, (LocationListener) this);
You can also set the frequency of updates. If you need something highly precise, take a bunch of readings over a few seconds. Then look at the "accuracy" number on each reading. Toss out any readings whose accuracy is significantly less accurate than the others. Then average the rest...
That's a pretty basic algorithm, and i'm getting accuracy within 1-2 feet on a galaxy S5 in the US.
If you use lower accuracy, it's going to average gps data with wifi and cellular results. GPS consumes more battery, so it uses it less often on this setting. Wifi uses a physical address lookup, since its always moving me towards the public road near my house, even when I'm in the middle of it.

Categories

Resources