I'm implementing an app that gets your location when you open it. It only gets it when the activity is created, so I don't need a LocationListener. I'm testing it in two real devices.
First I try to get the location using GPS_PROVIDER. If the result is NULL, I use NETWORK_PROVIDER. Since I'm testing it inside a building is to be expected that I won't be able to get the location using the GPS provider.
In one of the devices the location using GPS_PROVIDER is NULL, and the NETWORK_PROVIDER returns the correct location. But in the other device the location using GPS_PROVIDER is not NULL, but it's wrong (it's in a different city than the one I'm currently am!). This is the code I'm using:
private void getPosition() {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
myloc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(myloc == null)
myloc = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(myloc != null){
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> addresses = geoCoder.getFromLocation(myloc.getLatitude(), myloc.getLongitude(), 1);
if(addresses.size()>0){
String add = "";
for(int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i)+"\n";
placeEdit.setText(add);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
How can I know the location returned by the GPS provider is wrong? Should I look the network provider first and if it's null use the gps? This app is supposed to be used outside, so I'd like to use the gps first since it's more accurate.
Thanks!
As state in Android Documentation
getLastKnownLocation(String provider)
Returns a Location indicating the data from the last known location fix obtained from the given provider.
So when your device obtained position 2h earlier and in the meantime never get fresh fix, Location object return that old position. I suggest you to use LocationListener but with thread that will stop listening after some period of time - this approach prevent device from long fix-searching in case of bad view to satellites or when you are inside a building. If LocationListener obtain position use it, if not - use NETWORK_PROVIDER.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With