package dk.thoerup.traininfo; import java.util.List; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.util.Log; public class LocationLookup implements LocationListener{ LocationManager locManager; Context cntx; Handler hndl; Location lastKnownLocation = null; Location savedLocation = null; boolean isSearching = false; boolean hasGps; public LocationLookup(Context c, Handler h) { cntx = c; hndl = h; } public boolean hasLocation() { return savedLocation != null; } public Location getLocation() { return savedLocation; } public Location getLastKnownLocation() { return lastKnownLocation; } public void locateStations() { isSearching = true; hasGps = false; locManager = (LocationManager) cntx.getSystemService(Context.LOCATION_SERVICE); List providers = locManager.getProviders(true); if (providers.size() > 0) { for(String provider : providers) { Log.i("Provider", ""+provider); if (provider.equalsIgnoreCase("gps")) hasGps = true; locManager.requestLocationUpdates(provider, 0, 0, this); Location tmpLastKnown = locManager.getLastKnownLocation(provider); if (tmpLastKnown != null) { saveLastKnownLocation(tmpLastKnown); } } } else { // message that no suitable provider was found hndl.sendEmptyMessage(StationList.NOPROVIDER); } } @Override public void onLocationChanged(Location location) { if (isSearching == false) return; Log.i("Location", "Got location fix " + location.getLatitude() + ", " + location.getLongitude() + " accuracy=" + location.getAccuracy() + " provider=" +location.getProvider()); if (savedLocation == null || location.getAccuracy() < savedLocation.getAccuracy()) savedLocation = new Location(location); //save a copy if (hasGps) { if (!location.getProvider().equals("gps")) { return; // at least give the gps a chance } else if (location.getAccuracy() > 512) { return; //if we have a gps provider lets wait for a more precise fix } } stopSearch(); hndl.sendEmptyMessage(StationList.GOTLOCATION); } private void saveLastKnownLocation(Location loc) { if (lastKnownLocation == null) { lastKnownLocation = loc; } else { if (loc.getTime() > lastKnownLocation.getTime()) {//if loc is more recent than saved lastKnownLocation = loc; } } } public void stopSearch() { if (isSearching) { isSearching = false; locManager.removeUpdates(this); } } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }