ユーザーの現在の位置に基づいて最も近い場所を取得する GPS Android アプリケーションを構築しています。最初に、GPS とネットワークの両方を検出して、それらが有効になっているかどうかを確認します。両方が有効になっている場合は、GPS が最も正確であるため、最初に GPS を使用します。私のアプリケーションでは、GPS が屋外にあると想定しても安全です。したがって、GPS の取得にそれほど時間がかかることはありません。それでも、GPS に時間がかかる状況は常にあります。したがって、たとえば 2 分ほど GPS が使用された場合に 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
方法です。緯度/経度の値を取得してサーバーに送信し、適切な処理を行います。
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 に切り替えるのに時間がかかりすぎる場合、何を追加する必要がありますか?