Battery Conscious: Using your GPS with Android
Saturday, February 6, 2010 at 8:14PM With that Android OS it is straight forward to use your GPS to get your location. Starting out you may get your location manager and register for updates so your program get’s notified of changes in position. It may look something like this:
LocationManager locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
if (location != null)
{
Toast.makeText(getBaseContext(),
"Position: latitude [" +
location.getLatitude() +
"] longitude [" + location.getLongitude()+"]",
Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider,
int status, Bundle extras)
{
}
};
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);
This is a typical example you might see floating around on the internet or in an Android Pro book. The line that requests location updates takes the following parameters
1. GPS Provider
2. Minimum time between updates in milliseconds
3. Minimum distance between updates in meters
4. Location Listener
The above implementation will actually keep you GPS active all the time and drain your battery in less than 5 hours. It also doesn’t take into account your actual needs when specifying the location provider, in this case the GPS. Let’s take a look at how to improve this code to save battery life.
The first thing you can do is set up criteria based on your needs to get the best GPS provider available. For instance, if you only need to get your location (lat, lon) without any information on bearing or speed, and require that the battery have at least a medium charge to use the GPS then you can do so. The following example uses Criteria to get the best GPS provider and limits the time and distance between updates to save battery life.
private void SetupGPSListener()
{
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
// Indicates whether the provider is allowed to incur monetary cost.
criteria.setCostAllowed(true);
// Most location sensitive apps will need to be reactive to user movement.
// Simply polling the Location Manager will not force it to get new updates from the Location Providers.
// Use the requestLocationUpdates method to get updates whenever the current location changes
// the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power,
// and actual time between location updates may be greater or lesser than this value.
int minTimeBetweenUpdatesms = 1000 * 60;
// the minimum distance interval for notifications, in meters
int minDistanceBetweenUpdatesMeters = 20; // 100 ft
// Enable location providers
// This method enables each provider and returns the last known location.
// Also requests periodic updates for each provider to force android to start updating the locations for the other applications.
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, minTimeBetweenUpdatesms, minDistanceBetweenUpdatesMeters, new LocationListener() {
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
public void onProviderDisabled(String provider) {
// Update application if provider disabled.
Log.i(LOG_TAG, "GPS Provider is disabled");
}
public void onProviderEnabled(String provider) {
// Update application if provider enabled.
Log.i(LOG_TAG, "GPS Provider is enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
});
}
Rory |
12 Comments |
Reader Comments (12)
Thanks for taking the time to talk about this, I feel fervently about this and I take pleasure in learning about this topic. Please, as you gain information, please update this blog with more information. I have found it very useful. marc jacobs eyewear
Yeah thats great Information I had a bad experience with one of my own apps eating my battery.. What about onPause() /onResume() is there any need modify these methods when the locationListener is running ? and if so whats the best way?
It is a terrific write-up. Wow, numerous of those points I never assumed of in advance of. I frequently go through posts, even on this internet site, and I think they are wonderful, but I don't take the time to leave a comment. I'm going to get started on leaving a lot more feedback for sure.
Your article is nice, I read your article to learn a lot and hope to see your next article, look forward to your masterpiece, you can also see our simple wedding gowns
information, I hope it can give you You some convenient.
Wow, you might say that the technology is very good! Photo, so beautiful, very clear, wish you good luck, create the future together! And I share my blog http://www.shirts-sneakers.com/
New Air Max 2011 is the most popular of running shoes. The Nike Air Max 2010 shoes design, by high performance style. Nike Air Max Zenyth is a kind of wear-resisting, deft, comfortable and fashion Mens Nike Air Max LTD shoes.
Nike Air Max Skyline is special for sports and of the design.This is a high quality of Nike Air Max BW shoes and wear comfortable Air Max 90 shoes, easy. If you are a sports, that we suggest you buy Cheap Air Max 2011|Women's Nike Air Max 4-27|Nike Air Max TN shoes, you will not regret it.
Every woman longs to have set their own victoria bikini,Put on fashionable and beautiful victorias Secret bikini| Sinful Bikini playing on the seashore is every woman's dream,But, there are other words of good, the most beautiful may not be the most suitable, the most suitable is the most beautiful。Wear on the, the world is you. This summer, you wear Ed Hardy Bikini ?
Life has a lot of fun and beer and skittles is indispensable to life。Many people in the holiday with his family to climb up the mountain,Mountain climbing can exercise, it is a kind of fun, exciting and dangerous things.Mountain climbing, our security to our feet, a pair of good wear comfortable Vibram FiveFingers Sprint|Vibram FiveFingers Bikila will bring us a good luck. Have good vibram five fingers kso|Vibram FiveFingers shoes|vibram five fingers shoes sale|Vibram FiveFingers Womenwith happiness, friends, the happy home with you.
Want to buy a sexy Chanel Bikinis|Sinful Bikinis|ED Hardy Bikinis|Hollister Bikinis that can win you all the attention this summer? Get into this for the latest collection of sexy Louis Vuitton Bikinis|Gucci Bikini|juicy Bikinis swim wear swim wear and oakley sunglass sale.
We eat lunch discount nike shoeswith them and cheap nikes shoesoften welcome
them intolouboutins heels our business 6 rings new jordansfamily. But, at the
end of hot pink and black nikesthe day, our mbt shoes ebayresponsibility is to do
the rightnike high top sneakers thing for discount nike shoes saleour business
and the other new nike shoes 2011members of mbt shoes websiteour business family. No
one wins discount vibram five fingersif financial mbt shoes discontinuedtrauma is
the consequence of new nike air maxkeeping the cheap nikes shoesmarginal
employees nike low top basketball shoeson the hot nikes for womenteam. Hiring
the wrong person new air jordan shoesfor the job is an accident - keeping them around for too long is a mistake.
Hi there, You have done a great job. I’ll definitely digg it and personally suggest to my friends. I am sure they will be benefited from this website.
Houton Home Security
moncler jackets
ugg boots for women
monster beats
wedding dresses
chi flat iron
Your website have very interesting article. I got knowledge from here. Besides that, your blog is so popular among the searchers from search engines. It means yours website is very goodAlarm Monitoring Houston [url=http://www.smithmonitoring.com/houston-security/]Alarm Monitoring Houston[/url]
Your website have very interesting article. I got knowledge from here. Besides that, your blog is so popular among the searchers from search engines. It means yours website is very goodHouston Home Security
chi hair straightener
beats by dre