我想要获得 5 个连续的更新位置,以检查用户是否在移动并确保 GPS 已校准。我做了以下事情:
我将 android.permission.ACCESS_FINE_LOCATION"添加到 list 和 onConnected 中:
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
mLocationRequest.setFastestInterval(1000);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
在 onLocationChanged 中我执行了以下操作:
locationRetries++;
switch (locationRetries) {
case 1: {
firstLatitude = location.getLatitude();
firstLongitude = location.getLongitude();
}
case 5: {
locationRetries = 0;
lastLatitude = location.getLatitude();
lastLongitude = location.getLongitude();
accuracy = Math.round(location.getAccuracy());
stopLocationUpdates();//will remove from location updates and disconnects
float[] results = new float[1];
Location.distanceBetween(firstLatitude, firstLongitude, lastLatitude, lastLongitude, results);
if (results[0] > 5)... //if moved at least 5meters, show popup that the user is moving else do your thing
}
现在我有 3 个问题:
1) 尽管我将两个参数都设置为 1000 毫秒,但检索 5 个更新所需的时间似乎远少于 5 秒。
2) 尽管我走得很快,但所有 5 个位置(至少第一个和最后一个)都是相同的位置。我想我可能移动得太慢了
3)我关闭了我的应用程序,在远处重新打开它并按下了按钮。我几乎立刻就找到了之前的位置。我再次按下按钮,然后我就得到了我所在的真实位置。就好像它并没有真正询问/等待 GPS 的位置,而是获取了当时远远不准确的最后一个位置。我没有任何“获取最后已知位置”代码。
我想底线是:当我询问位置时,以及连续 5 次询问 GPS 时,我如何确保它真正询问我在哪里,以给我真实的位置,而不是来自缓存(?)。
最佳答案
intelligently manages the underlying location technology and gives you the best location according to your needs.
- Simple APIs: Lets you specify high-level needs like "high accuracy" or "low power", instead of having to worry about location providers.
- Immediately available: Gives your apps immediate access to the best, most recent location.
- Power-efficiency: Minimizes your app's use of power. Based on all incoming location requests and available sensors, fused location provider chooses the most efficient way to meet those needs.
- Versatility: Meets a wide range of needs, from foreground uses that need highly accurate location to background uses that need periodic location updates with negligible power impact.
无法保证融合位置提供商将永远使用 GPS - 如果其最近的位置达到您请求的精度,它将返回,直到返回更好的位置(即实时 GPS 返回准确的位置)。这可确保您更快地获得更好的位置,而无需等待 GPS 启动。
如果您特别需要 GPS 数据,则需要使用 LocationManager使用GPS_PROVIDER .
如果您尝试确定用户当前正在做什么,则可以使用 ActivityRecognitionApi ,返回 DetectedActivity例如 WALKING 或 STILL:使用它可以提供更快的方法来了解用户当前正在做什么。
关于Android 位置更新频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27851816/