Joh*_* Au 5 gps android location locationmanager location-provider
我正在构建一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是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);
}
Run Code Online (Sandbox Code Playgroud)
无论使用 GPS 还是网络,您都无法大幅减少获取位置的最终等待时间。
这两种定位方法各有优缺点:
GPS 通常需要更长的时间才能知道您的位置,因为寻找和校准 GPS 卫星是一项艰巨的任务(需要找到至少3 颗正确对齐的卫星)。最重要的是,添加最终阻碍信号的物体/环境。除非您在应用程序启动之前/启动时启用 GPS,否则必须等待。另一方面,您可以获得细粒度的位置。
如果您只需要一个大概的位置,使用网络是一个解决方案:它会在几秒钟内返回数据。然而,位置的精确度取决于可用/使用的网络;我没有任何实际的例子,但我想精度可能会有很大差异。GPS始终比网络提供更精确的位置。
了解没有预定义的选择。一切都取决于您的应用程序如何处理这些数据。
如果可用,请使用 GPS,同时向网络发出位置请求,如果没有 GPS 设备,则回退到网络。然后采取:
如果 GPS 或网络无法检索位置(例如 2 分钟),我们就会更换提供商。我们不希望用户等待太久。
在这两种情况下,都不要设置后备计时器:在第一个提供程序失败的情况下,您只会延长等待时间;所以这两个请求同时进行,除非 android API 不允许异步位置请求。
| 归档时间: |
|
| 查看次数: |
1189 次 |
| 最近记录: |