我正在构建一个GPS Android应用程序,它根据用户的当前位置获取最近的位置。
这就是我的申请:
我希望做什么:
如果GPS或网络无法检索位置(例如2分钟),那么我们会切换提供商。我们不希望用户等待太久。
能够使用两个提供商并从中获得最准确的提示也是很好的。我看了http://developer.android.com/guide/topics/location/strategies.html,看到了isBetterLocation方法。我如何在我的应用程序中集成此方法?我无法理解应该如何,何时何地调用它。我假设isBetterLocation()要求我同时调用网络和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
方法。我得到lat / lng值,然后将它们发送到我的服务器,然后用它做适当的东西。
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);
}
答案 0 :(得分:0)
使用GPS或网络,您无法大幅缩短最终等待时间以获取您的位置。
这两种定位方法都有其缺点和优点:
GPS通常需要更长的时间才能知道您的位置,因为查找和校准GPS卫星是一项艰巨的任务(至少需要 3 3个正确对齐的卫星)。最重要的是,添加阻挡信号的最终阻碍物体/环境。除非您在应用开始之前/之后启用GPS,否则必须等待。 另一方面,您将获得一个细粒度的位置。
如果您只需要一个粗略的位置,使用网络是一种解决方案:它会在几秒钟内返回数据。 然而位置的精确度取决于可用/使用的网络;我没有任何实际的例子,但我猜精度可以大大变化。 GPS ALWAYS 的位置比网络更好。
了解没有预定义的选择。任何事情都取决于你的应用对这些数据的作用。
如果可用,请使用GPS,同时向网络发出位置请求,如果没有GPS设备,则退回到网络。然后采取:
如果GPS或网络无法检索位置(例如2分钟),那么我们会切换提供商。我们不希望用户等待太久。
在这两种情况下,都不要制作后备计时器:在第一个提供商失败的情况下,你只需要延长等待时间;所以两个请求同时进行,除非android API不允许异步位置请求。