1

我正在构建一个 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?

4

1 回答 1

1

我建议同时使用这两个提供程序并使用例如本文中的 isBetterLocation() 函数确定更准确的位置:http: //developer.android.com/guide/topics/location/strategies.html。在这种情况下,如果 GPS 速度较慢,用户无需等待 2 分钟即可使用您的应用。首先,您将使用网络更新,然后在获得 GPS 定位时,使用更准确的位置。

于 2013-03-08T17:01:07.350 回答