我正在构建一个 GPS Android 应用程序,它可以根据用户的当前位置检索最近的地点。首先,我同时检测 GPS 和网络以查看它们是否已启用。如果两者都启用,我会首先使用 GPS,因为它是最准确的,并且对于我的应用程序,假设它们在室外是安全的,因此,检索 GPS 应该不会花费太长时间。然而,GPS 总是需要很长时间的情况。因此,如果 GPS 接管,例如 2 分钟,我如何实现切换到 NETWORK_PROVIDER 的方法?
这是我现在的代码:
我检查是否启用了 GPS 或互联网。
if(!GPSEnabled && !networkEnabled)
{
Toast.makeText(this, "Error: This application requires a GPS or network connection",
Toast.LENGTH_SHORT).show();
}
else
{
if(GPSEnabled)
{
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else if(networkEnabled)
{
System.out.println("Getting updates from network provider");
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
}
这是 onLocationChanged
方法。我得到纬度/经度值,然后将它们发送到我的服务器,然后用它做适当的事情。
public void onLocationChanged(Location location)
{
//Get coordinates
double lat = (location.getLatitude());
double lng = (location.getLongitude());
Log.d("MainActivity", "got location: " + lat + ": " + lng);
//get nearest locations
new GetLocations().execute(SharedVariables.root + SharedVariables.locationsController + SharedVariables.getNearestMethod + lat + "/" + lng);
// Zoom in, animating the camera after the markers have been placed
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
System.out.println("lat = " + lat + ", lng = " + lng);
//Stop listening for updates. We only want to do this once.
locManager.removeUpdates(this);
}
如果切换到网络或 GPS 花费的时间太长,我需要添加什么?
最佳答案
我建议同时使用这两个提供程序并使用例如本文中的 isBetterLocation() 函数来确定更准确的位置:http://developer.android.com/guide/topics/location/strategies.html .在这种情况下,如果 GPS 速度较慢,用户无需等待 2 分钟即可使用您的应用。首先,您将使用网络更新,然后在获得 GPS 定位后,获得更准确的位置。
关于android - 尝试检索位置修复时等待 'x' 时间量后如何切换提供商?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15297626/