I've got this working:
private void _getLocation() {
// Get the location manager
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
}
It's simple. It gets the best available provider and gets its last known position.
If you want it only with the GPS, try this.
Hope it helps!
EDITED:
try this:
private void _getLocation() {
// Get the location manager
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
locationManager
.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
location = locationManager.getLastKnownLocation(bestProvider);
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
}
This code gets the last known location and then do a request for the actual location.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…