Reputation: 2519
I have the following code in my Service:
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider =
locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
Location location = locationManager.getLastKnownLocation(provider);
while(true)
{
if(...)//every 5 seconds it gets into
{
....//control if the location is not null
lat = location.getLatitude();
lon = location.getLongitude();
alt = location.getAltitude();
Log.i(TAG, "Latitude: "+lat+"\nLongitude: "+lon+"\nAltitude: "+alt);
}
else {
Log.i(TAG, "Error!");
}
}
This code kind of works in my emulator (GPS are inserted into the Log
), but in my Mobile device, this code gets to the else
branch. Could somebody tell me where is the problem? In my code or in my Mobile device? Thanks in advance.
P.S.: The GPS is turned on, in another apps it works.
Upvotes: 0
Views: 648
Reputation: 4705
getLastKnownLocation()
will not fetch subsequent location from the GPS provider. It will return (as the name may suggest) the last known location requested by some code. I assume that you check location being not null
in the condition, which is not shown in your code. The location is null if the device "decided" that the last known location is too old or unreliable by other means. You need to request location updates and provide a location listener to get locations repeatetly.
There are lots of tutorials available. Here ist one. of them.
Upvotes: 1