We should use the
LocationManager
.LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to
getLastKnownLocation()
doesn't block - which means it will return null
if no position is currently available - so you probably want to have a look at passing a LocationListener
to therequestLocationUpdates()
method instead, which will give you asynchronous updates of your location.private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
Required Permission :
You'll need to give your application the
ACCESS_FINE_LOCATION
permission if you want to use GPS.<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the
ACCESS_COARSE_LOCATION
permission for when GPS isn't available and select your location provider with the getBestProvider()
method.