我正在尝试获取current
手机的位置,为此我使用GPS追踪器教程 http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/,问题总是使用该方法getLastKnownLocation
并返回旧位置。
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
你可以看教程使用getLastKnownLocation
使用时Network
or GPS
提供商,但我真的非常需要当前的职位。
我不知道怎么得到它!
将 Fused Location Provider API 与 GoogleApiClient 结合使用。你可以找到apihere https://developer.android.com/reference/com/google/android/gms/location/FusedLocationProviderApi.html。它们旨在提供高精度的位置。使用 GoogleApiClient 来使用它。
new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build()
还有其他使用位置提供程序的方法。您不应将自己限制在使用 GPS 和移动网络获取的位置。而是迭代所有位置提供程序,并根据您的准确性要求选择那些为您提供高精度的位置提供程序。以下代码执行此操作:
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestAge = Long.MIN_VALUE;
List<String> matchingProviders = mLocationManager.getAllProviders();
for (String provider : matchingProviders) {
Location location = mLocationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if (accuracy < bestAccuracy) {
bestResult = location;
bestAccuracy = accuracy;
bestAge = time;
}
}
}
// Return best reading or null
if (bestAccuracy > minAccuracy
|| (System.currentTimeMillis() - bestAge) > maxAge) {
return null;
} else {
return bestResult;
}
您还可以在检查位置对象的准确性后直接使用它们。您应该利用其他应用程序访问的位置,而不仅仅是依赖 GPS/移动网络获取的位置。
如果您想连续侦听位置更新,请实现 Locationlistener 回调以连续获取位置更新。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)