3

I always had some difficulties to find a good way for the instant location of the device. What I want to do is once per use of the app (e.g. when the onCreate of an activity is called) i want to know the coordinates of the device in that exact moment and never ask for them again. What I think could be the best way is to have something like a static Class with a function similar to :

coordinates getCoordinates();

Some advice/snippet to give?

aveschini
  • 1,592
  • 3
  • 20
  • 39

2 Answers2

6

Use LocationManager.getLastKnownLocation or LocationManager.requestSingleUpdate.

The first will return immediately, but may return null if no location is already available.

The second will return your data on a callback, but will wake up whatever provider is needed and will get a good location (if possible).

appersiano
  • 2,450
  • 23
  • 40
Gabe Sechan
  • 84,451
  • 9
  • 82
  • 121
2

I have found what I really was searching in THIS answer.

I have only added two controls; i check if:

  • gps_loc.getTime() (or net_loc.getTime()) is bigger than System.currentTimeMillis() - 300000 (5 minutes ago). In the method run() of the inner class GetLastLocation;
  • location.getAccuracy() < 100. In the method onLocationChanged() of both LocationListeners (network and GPS).

Hope it helps!

Community
  • 1
  • 1
aveschini
  • 1,592
  • 3
  • 20
  • 39