问题
I'm trying to implement an application which senses position from both GPS and the network provider and shows it on a Google Map. I succeeded in doing this, but I have a question: I get the provider in the onCreate() of my Activity (it extends LocationListener)
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
It works fine, my problem is that when onLocationChange() is called, I should act differently if the provider which called it is GPS or NETWORK. Is there a way to know which? To be more clear:
When onLocationChanged(Location location)
is called, is there a chance to know which provider made the call? I have tried using an if
on the provider string but it seems it doesn't work.
回答1:
Do you need to know the Location provider (GPS, WIFI or Network) or its accuracy?
getAccuracy()
Get the estimated accuracy of this location, in meters.
We define accuracy as the radius of 68% confidence. In other words, if you draw a circle centered at this location's latitude and longitude, and with a radius equal to the accuracy, then there is a 68% probability that the true location is inside the circle.
If you really care about the provider, you could probably use isProviderEnabled().
回答2:
check that accuracy is <= 30m:
boolean isGPS = (location.getAccuracy() <= 30);
回答3:
I think you wanna know which provider provided last Location update .....
u have created Provider as a string just use that String in code like if (provider.matches("GPS")){}
回答4:
I see several answers, and although they may be useful, none addresses the actual question asked:
When onLocationChanged(Location location) is called, is there a chance to know which provider made the call?
To know whether it was GPS_PROVIDER
or NETWORK_PROVIDER
the one triggering the onLocationChanged
you can use the getProvider()
method (or the provider
value in Kotlin):
@Override
public void onLocationChanged(Location location){
//obtain a string, 'gps' or 'network', from the location
System.out.println(location.getProvider());
}
Or in Kotlin:
override fun onLocationChanged(location: Location?) {
println(location!!.provider)
}
Doc reference here
来源:https://stackoverflow.com/questions/15321926/android-how-to-know-if-location-detected-is-from-gps-or-network-provider