我正在构建一个 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
方法。我得到 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);
}
如果任一时间太长,我需要添加什么才能切换到网络或 GPS?