Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Get Location Only One Time

i need to get the current user location on an android app, so i've read some tutorials and samples on the web, but i see that in all the examples, the location is retrived from a "onLocationChange" that mean that every time the location change, the code in the "onLocationChange" is executed.

i need only to get the user location at the moment the app is started.

Thanks for your help!

like image 846
Marco Faion Avatar asked Jan 19 '11 13:01

Marco Faion


People also ask

How many ways can you get location on Android?

There are two ways to get a users location in our application: android. location. LocationListener : This is a part of the Android API.

What is a fused location?

The fused location provider is a location API in Google Play services that intelligently combines different signals to provide the location information that your app needs.

How do you subtract time on Android?

long totalTime = endDate. getTime() - startDate. getTime();


2 Answers

You can get the last know location using the code below. It gets the location providers and loops over the array backwards. i.e starts with GPS, if no GPS then gets network location. You can call this method whenever you need to get the location.

private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
List<String> providers = lm.getProviders(true);

/* Loop over the array backwards, and if you get an accurate location, then break                 out the loop*/
Location l = null;

for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}

double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
like image 170
Phobos Avatar answered Oct 02 '22 05:10

Phobos


You can do this with LocationManager.getLastKnownLocation

like image 44
Eric Levine Avatar answered Oct 02 '22 07:10

Eric Levine