如何在等待' x'之后切换提供商?尝试检索位置修复时的时间量?

时间:2013-03-08 15:35:18

标签: android networking gps locationmanager google-maps-android-api-2

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

1 个答案:

答案 0 :(得分:1)

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