diff options
author | Samuel Tardieu <sam@rfc1149.net> | 2012-04-27 12:10:34 +0200 |
---|---|---|
committer | Samuel Tardieu <sam@rfc1149.net> | 2012-04-27 12:10:34 +0200 |
commit | 5a10f40f72702009d2afc3bc6501b8843a70bb03 (patch) | |
tree | 95185ab6c5d83d53a461f1c9f57d6e892b9bcc0c /main | |
parent | af61aa12c6b9e0adffc69bae94a0ae28f9c3db7b (diff) | |
download | cgeo-5a10f40f72702009d2afc3bc6501b8843a70bb03.zip cgeo-5a10f40f72702009d2afc3bc6501b8843a70bb03.tar.gz cgeo-5a10f40f72702009d2afc3bc6501b8843a70bb03.tar.bz2 |
Use the IGeoData interface and Observer pattern to update location
Diffstat (limited to 'main')
30 files changed, 737 insertions, 890 deletions
diff --git a/main/src/cgeo/geocaching/CacheDetailActivity.java b/main/src/cgeo/geocaching/CacheDetailActivity.java index 01d57f3..e71ddd4 100644 --- a/main/src/cgeo/geocaching/CacheDetailActivity.java +++ b/main/src/cgeo/geocaching/CacheDetailActivity.java @@ -30,7 +30,6 @@ import cgeo.geocaching.utils.UnknownTagsHandler; import com.viewpagerindicator.TitlePageIndicator; import com.viewpagerindicator.TitleProvider; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; @@ -124,7 +123,6 @@ public class CacheDetailActivity extends AbstractActivity { private static final String CALENDAR_ADDON_URI = "market://details?id=cgeo.calendar"; - private cgGeo geolocation; private cgCache cache; private final Progress progress = new Progress(); private SearchResult search; @@ -188,10 +186,6 @@ public class CacheDetailActivity extends AbstractActivity { setContentView(R.layout.cacheview); setTitle(res.getString(R.string.cache)); - if (geolocation == null) { - geolocation = app.startGeo(locationUpdater); - } - String geocode = null; String guid = null; String name = null; @@ -330,9 +324,7 @@ public class CacheDetailActivity extends AbstractActivity { public void onResume() { super.onResume(); - if (geolocation == null) { - geolocation = app.startGeo(locationUpdater); - } + app.addGeoObserver(locationUpdater); if (refreshOnResume) { notifyDataSetChanged(); refreshOnResume = false; @@ -341,19 +333,11 @@ public class CacheDetailActivity extends AbstractActivity { @Override public void onDestroy() { - if (geolocation != null) { - geolocation = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geolocation != null) { - geolocation = app.removeGeo(); - } - if (cache != null) { cache.setChangeNotificationHandler(null); } @@ -363,9 +347,7 @@ public class CacheDetailActivity extends AbstractActivity { @Override public void onPause() { - if (geolocation != null) { - geolocation = app.removeGeo(); - } + app.deleteGeoObserver(locationUpdater); super.onPause(); } @@ -514,14 +496,14 @@ public class CacheDetailActivity extends AbstractActivity { case CONTEXT_MENU_WAYPOINT_DEFAULT_NAVIGATION: { final cgWaypoint waypoint = cache.getWaypoint(index); if (waypoint != null) { - NavigationAppFactory.startDefaultNavigationApplication(geolocation, this, null, waypoint, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, null, waypoint, null); } } break; case CONTEXT_MENU_WAYPOINT_NAVIGATE: { final cgWaypoint waypoint = cache.getWaypoint(contextMenuWPIndex); if (waypoint != null) { - NavigationAppFactory.showNavigationMenu(geolocation, this, null, waypoint, null); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, null, waypoint, null); } } break; @@ -597,7 +579,7 @@ public class CacheDetailActivity extends AbstractActivity { } return false; } - if (NavigationAppFactory.onMenuItemSelected(item, geolocation, this, cache, null, null)) { + if (NavigationAppFactory.onMenuItemSelected(item, app.currentGeo(), this, cache, null, null)) { return true; } if (GeneralAppsFactory.onMenuItemSelected(item, this, cache)) { @@ -710,12 +692,9 @@ public class CacheDetailActivity extends AbstractActivity { progress.dismiss(); } - private class LocationUpdater implements UpdateLocationCallback { + private class LocationUpdater extends GeoObserver { @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } + public void updateLocation(final IGeoData geo) { if (cacheDistanceView == null) { return; } @@ -723,13 +702,13 @@ public class CacheDetailActivity extends AbstractActivity { try { StringBuilder dist = new StringBuilder(); - if (geo.coordsNow != null && cache != null && cache.getCoords() != null) { - dist.append(HumanDistance.getHumanDistance(geo.coordsNow.distanceTo(cache.getCoords()))); + if (geo.getCoordsNow() != null && cache != null && cache.getCoords() != null) { + dist.append(HumanDistance.getHumanDistance(geo.getCoordsNow().distanceTo(cache.getCoords()))); } if (cache != null && cache.getElevation() != null) { - if (geo.altitudeNow != null) { - double diff = (cache.getElevation() - geo.altitudeNow); + if (geo.getAltitudeNow() != null) { + double diff = (cache.getElevation() - geo.getAltitudeNow()); if (diff >= 0) { dist.append(" ↗"); } else if (diff < 0) { @@ -864,7 +843,7 @@ public class CacheDetailActivity extends AbstractActivity { } //TODO: previously this used also the search argument "search". check if still needed - NavigationAppFactory.startDefaultNavigationApplication(geolocation, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, cache, null, null); } /** @@ -877,7 +856,7 @@ public class CacheDetailActivity extends AbstractActivity { } //TODO: previously this used also the search argument "search". check if still needed - NavigationAppFactory.startDefaultNavigationApplication2(geolocation, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication2(app.currentGeo(), this, cache, null, null); } /** @@ -895,7 +874,7 @@ public class CacheDetailActivity extends AbstractActivity { } private void showNavigationMenu() { - NavigationAppFactory.showNavigationMenu(geolocation, this, cache, null, null); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, cache, null, null); } /** @@ -1517,10 +1496,6 @@ public class CacheDetailActivity extends AbstractActivity { } } - if (geolocation != null) { - locationUpdater.updateLocation(geolocation); - } - return view; } @@ -2403,13 +2378,13 @@ public class CacheDetailActivity extends AbstractActivity { wpNavView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - NavigationAppFactory.startDefaultNavigationApplication(geolocation, CacheDetailActivity.this, null, wpt, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), CacheDetailActivity.this, null, wpt, null); } }); wpNavView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { - NavigationAppFactory.startDefaultNavigationApplication2(geolocation, CacheDetailActivity.this, null, wpt, null); + NavigationAppFactory.startDefaultNavigationApplication2(app.currentGeo(), CacheDetailActivity.this, null, wpt, null); return true; } }); diff --git a/main/src/cgeo/geocaching/GeoDataProvider.java b/main/src/cgeo/geocaching/GeoDataProvider.java new file mode 100644 index 0000000..b7a5341 --- /dev/null +++ b/main/src/cgeo/geocaching/GeoDataProvider.java @@ -0,0 +1,371 @@ +package cgeo.geocaching; + +import cgeo.geocaching.enumerations.LocationProviderType; +import cgeo.geocaching.geopoint.Geopoint; +import cgeo.geocaching.go4cache.Go4Cache; +import cgeo.geocaching.utils.Log; +import cgeo.geocaching.utils.MemorySubject; + +import android.content.Context; +import android.location.GpsSatellite; +import android.location.GpsStatus; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.os.Bundle; + +import java.util.Iterator; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * Provide information about the user location. This class should be instantiated only once per application. + */ +class GeoDataProvider extends MemorySubject<IGeoData> { + + private static final String LAST_LOCATION_PSEUDO_PROVIDER = "last"; + private final LocationManager geoManager; + private final AbstractLocationListener networkListener = new NetworkLocationListener(); + private final AbstractLocationListener gpsListener = new GpsLocationListener(); + private final GpsStatusListener gpsStatusListener = new GpsStatusListener(); + private Location locGps = null; + private Location locNet = null; + private long locGpsLast = 0L; + private GeoData current = new GeoData(); + private final Unregisterer unregisterer = new Unregisterer(); + + final private cgeoapplication app; + + private static class GeoData implements Cloneable, IGeoData { + public Location location = null; + public LocationProviderType locationProvider = LocationProviderType.LAST; + public Geopoint coordsNow = null; + public Double altitudeNow = null; + public float bearingNow = 0; + public float speedNow = 0; + public float accuracyNow = -1f; + public int satellitesVisible = 0; + public int satellitesFixed = 0; + + @Override + public Location getLocation() { + return location; + } + + @Override + public LocationProviderType getLocationProvider() { + return locationProvider; + } + + @Override + public Geopoint getCoordsNow() { + return coordsNow; + } + + @Override + public Double getAltitudeNow() { + return altitudeNow; + } + + @Override + public float getBearingNow() { + return bearingNow; + } + + @Override + public float getSpeedNow() { + return speedNow; + } + + @Override + public float getAccuracyNow() { + return accuracyNow; + } + + @Override + public int getSatellitesVisible() { + return satellitesVisible; + } + + @Override + public int getSatellitesFixed() { + return satellitesFixed; + } + + public IGeoData makeImmutable() { + try { + return (IGeoData) clone(); + } catch (final CloneNotSupportedException e) { + // This cannot happen + return null; + } + } + }; + + private class Unregisterer extends Thread { + + private boolean unregisterRequested = false; + private ArrayBlockingQueue<Boolean> queue = new ArrayBlockingQueue<Boolean>(1); + + public void cancelUnregister() { + try { + queue.put(false); + } catch (final InterruptedException e) { + // Do nothing + } + } + + public void lateUnregister() { + try { + queue.put(true); + } catch (final InterruptedException e) { + // Do nothing + } + } + + @Override + public void run() { + try { + while (true) { + if (unregisterRequested) { + final Boolean element = queue.poll(2500, TimeUnit.MILLISECONDS); + if (element == null) { + // Timeout + unregisterListeners(); + unregisterRequested = false; + } else { + unregisterRequested = element; + } + } else { + unregisterRequested = queue.take(); + } + } + } catch (final InterruptedException e) { + // Do nothing + } + } + + } + + /** + * Build a new geo data provider object. + * <p/> + * There is no need to instantiate more than one such object in an application, as observers can be added + * at will. + * + * @param app the application + */ + public GeoDataProvider(final cgeoapplication app) { + geoManager = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE); + restoreLastLocation(); + this.app = app; + unregisterer.start(); + // Start with an empty GeoData just in case someone queries it before we get + // a chance to get any information. + memory = new GeoData(); + } + + private void registerListeners() { + geoManager.addGpsStatusListener(gpsStatusListener); + + for (final AbstractLocationListener listener : new AbstractLocationListener[] { networkListener, gpsListener }) { + try { + geoManager.requestLocationUpdates(listener.locationProvider, 0, 0, listener); + } catch (final Exception e) { + Log.w("There is no location provider " + listener.locationProvider); + } + } + } + + private synchronized void unregisterListeners() { + // This method must be synchronized because it will be called asynchronously from the Unregisterer thread. + // We check that no observers have been re-added to prevent a race condition. + if (sizeObservers() == 0) { + geoManager.removeUpdates(networkListener); + geoManager.removeUpdates(gpsListener); + geoManager.removeGpsStatusListener(gpsStatusListener); + } + } + + @Override + protected void onFirstObserver() { + unregisterer.cancelUnregister(); + registerListeners(); + } + + @Override + protected void onLastObserver() { + unregisterer.lateUnregister(); + } + + private static abstract class AbstractLocationListener implements LocationListener { + private final String locationProvider; + + protected AbstractLocationListener(final String provider) { + locationProvider = provider; + } + + @Override + public void onStatusChanged(final String provider, final int status, final Bundle extras) { + // nothing + } + + @Override + public void onProviderDisabled(final String provider) { + // nothing + } + + @Override + public void onProviderEnabled(final String provider) { + // nothing + } + } + + private final class GpsLocationListener extends AbstractLocationListener { + + public GpsLocationListener() { + super(LocationManager.GPS_PROVIDER); + } + + @Override + public void onLocationChanged(final Location location) { + locGps = location; + locGpsLast = System.currentTimeMillis(); + selectBest(location.getProvider()); + } + } + + private final class NetworkLocationListener extends AbstractLocationListener { + + protected NetworkLocationListener() { + super(LocationManager.NETWORK_PROVIDER); + } + + @Override + public void onLocationChanged(final Location location) { + locNet = location; + selectBest(location.getProvider()); + } + + } + + private final class GpsStatusListener implements GpsStatus.Listener { + + @Override + public void onGpsStatusChanged(final int event) { + if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) { + final GpsStatus status = geoManager.getGpsStatus(null); + final Iterator<GpsSatellite> statusIterator = status.getSatellites().iterator(); + + int satellites = 0; + int fixed = 0; + + while (statusIterator.hasNext()) { + final GpsSatellite sat = statusIterator.next(); + if (sat.usedInFix()) { + fixed++; + } + satellites++; + } + + boolean changed = false; + if (satellites != current.satellitesVisible) { + current.satellitesVisible = satellites; + changed = true; + } + if (fixed != current.satellitesFixed) { + current.satellitesFixed = fixed; + changed = true; + } + + if (changed) { + selectBest(null); + } + } + } + } + + private void selectBest(final String signallingProvider) { + if (locNet != null && locGps == null) { // we have only NET + assign(locNet); + } + else if ((locNet == null && locGps != null) // we have only GPS + || (current.satellitesFixed > 0) // GPS seems to be fixed + || (signallingProvider != null && signallingProvider.equals(LocationManager.GPS_PROVIDER)) // we have new location from GPS + || locGpsLast > System.currentTimeMillis() - 30 * 1000 // GPS was working in last 30 seconds + ) { + assign(locGps); + } + else { + assign(locNet); // nothing else, using NET + } + notifyObservers(current.makeImmutable()); + } + + private void assignLastLocation(final Geopoint coords) { + if (coords == null) { + return; + } + + current.locationProvider = LocationProviderType.LAST; + current.coordsNow = coords; + current.altitudeNow = null; + current.bearingNow = 0f; + current.speedNow = 0f; + current.accuracyNow = 999f; + + notifyObservers(current.makeImmutable()); + } + + private void assign(final Location loc) { + if (loc == null) { + current.locationProvider = LocationProviderType.LAST; + return; + } + + current.location = loc; + + final String provider = current.location.getProvider(); + if (provider.equals(LocationManager.GPS_PROVIDER)) { + current.locationProvider = LocationProviderType.GPS; + } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) { + current.locationProvider = LocationProviderType.NETWORK; + } else if (provider.equalsIgnoreCase(LAST_LOCATION_PSEUDO_PROVIDER)) { + current.locationProvider = LocationProviderType.LAST; + } + + current.coordsNow = new Geopoint(current.location.getLatitude(), current.location.getLongitude()); + cgeoapplication.getInstance().setLastCoords(current.coordsNow); + + final Location location = current.location; + final LocationProviderType locationProvider = current.locationProvider; + current.altitudeNow = location.hasAltitude() && locationProvider != LocationProviderType.LAST ? location.getAltitude() + Settings.getAltCorrection() : null; + current.bearingNow = location.hasBearing() && locationProvider != LocationProviderType.LAST ? location.getBearing() : 0f; + current.speedNow = location.hasSpeed() && locationProvider != LocationProviderType.LAST ? location.getSpeed() : 0f; + current.accuracyNow = location.hasAccuracy() && locationProvider != LocationProviderType.LAST ? location.getAccuracy() : 999f; + + notifyObservers(current.makeImmutable()); + + if (locationProvider == LocationProviderType.GPS || locationProvider == LocationProviderType.NETWORK) { + // FIXME: should use observer pattern as well + Go4Cache.signalCoordinates(current.coordsNow); + } + } + + private void restoreLastLocation() { + // restore from last location (stored by app) + assignLastLocation(cgeoapplication.getInstance().getLastCoords()); + + // restore from last location (stored by device sensors) + for (final String provider : new String[] { LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER }) { + final Location lastLocation = geoManager.getLastKnownLocation(provider); + if (lastLocation != null) { + lastLocation.setProvider(LAST_LOCATION_PSEUDO_PROVIDER); + assign(lastLocation); + + Log.i("Using last location from " + provider); + break; + } + } + } +} diff --git a/main/src/cgeo/geocaching/GeoObserver.java b/main/src/cgeo/geocaching/GeoObserver.java new file mode 100644 index 0000000..8d5475f --- /dev/null +++ b/main/src/cgeo/geocaching/GeoObserver.java @@ -0,0 +1,13 @@ +package cgeo.geocaching; + +import cgeo.geocaching.utils.IObserver; + +public abstract class GeoObserver implements IObserver<IGeoData> { + + abstract protected void updateLocation(final IGeoData geo); + + @Override + public void update(final IGeoData geo) { + updateLocation(geo); + } +} diff --git a/main/src/cgeo/geocaching/UpdateLocationCallback.java b/main/src/cgeo/geocaching/UpdateLocationCallback.java deleted file mode 100644 index f0334a1..0000000 --- a/main/src/cgeo/geocaching/UpdateLocationCallback.java +++ /dev/null @@ -1,5 +0,0 @@ -package cgeo.geocaching; - -public interface UpdateLocationCallback { - public void updateLocation(cgGeo geo); -} diff --git a/main/src/cgeo/geocaching/apps/cache/navi/AbstractPointNavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/AbstractPointNavigationApp.java index bf7ebb1..c5abf7f 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/AbstractPointNavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/AbstractPointNavigationApp.java @@ -1,7 +1,7 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.geopoint.Geopoint; @@ -24,7 +24,7 @@ abstract class AbstractPointNavigationApp extends AbstractNavigationApp { } @Override - public final boolean invoke(cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, Geopoint coords) { + public final boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, Geopoint coords) { if (cache == null && waypoint == null && coords == null) { return false; } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/CompassApp.java b/main/src/cgeo/geocaching/apps/cache/navi/CompassApp.java index 3d804d9..720b85a 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/CompassApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/CompassApp.java @@ -1,8 +1,8 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeonavigate; import cgeo.geocaching.geopoint.Geopoint; @@ -22,7 +22,7 @@ class CompassApp extends AbstractNavigationApp { } @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { if (cache != null && cache.getGeocode() != null) { diff --git a/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java index 74141c3..e5001da 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java @@ -1,11 +1,11 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.Settings; +import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; -import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.utils.Log; @@ -26,7 +26,7 @@ class GoogleNavigationApp extends AbstractNavigationApp { } @Override - public boolean invoke(final cgGeo geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint coords) { + public boolean invoke(final IGeoData geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint coords) { if (activity == null) { return false; } @@ -50,8 +50,8 @@ class GoogleNavigationApp extends AbstractNavigationApp { return true; } - private static boolean navigateToCoordinates(cgGeo geo, Activity activity, final Geopoint coords) { - final Geopoint coordsNow = geo == null ? null : geo.coordsNow; + private static boolean navigateToCoordinates(IGeoData geo, Activity activity, final Geopoint coords) { + final Geopoint coordsNow = geo == null ? null : geo.getCoordsNow(); // Google Navigation if (Settings.isUseGoogleNavigation()) { diff --git a/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java b/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java index 44f151e..2f05459 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java @@ -1,8 +1,8 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; @@ -18,7 +18,7 @@ class InternalMap extends AbstractNavigationApp { } @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { if (cache != null) { CGeoMap.startActivityGeoCode(activity, cache.getGeocode()); diff --git a/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java b/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java index c867373..60e3315 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java @@ -1,9 +1,9 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; +import cgeo.geocaching.apps.AbstractLocusApp; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; -import cgeo.geocaching.apps.AbstractLocusApp; import cgeo.geocaching.geopoint.Geopoint; import android.app.Activity; @@ -20,7 +20,7 @@ class LocusApp extends AbstractLocusApp implements NavigationApp { * @author koem */ @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { final ArrayList<Object> points = new ArrayList<Object>(); diff --git a/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java index 119d27b..62629de 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java @@ -1,15 +1,15 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; +import cgeo.geocaching.apps.App; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; -import cgeo.geocaching.apps.App; import cgeo.geocaching.geopoint.Geopoint; import android.app.Activity; public interface NavigationApp extends App { - public boolean invoke(final cgGeo geo, final Activity activity, + public boolean invoke(final IGeoData geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint coords); } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java b/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java index 052189a..6f179ab 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java @@ -1,14 +1,13 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; -import cgeo.geocaching.SearchResult; import cgeo.geocaching.Settings; import cgeo.geocaching.StaticMapsProvider; +import cgeo.geocaching.apps.AbstractAppFactory; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeoapplication; -import cgeo.geocaching.apps.AbstractAppFactory; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.utils.Log; @@ -80,7 +79,7 @@ public final class NavigationAppFactory extends AbstractAppFactory { * A dialog is created for tool selection and the selected tool is started afterwards. * <p /> * Delegates to - * {@link #showNavigationMenu(cgGeo, Activity, cgCache, SearchResult, cgWaypoint, Geopoint, boolean, boolean)} with + * {@link #showNavigationMenu(IGeoData, Activity, cgCache, cgWaypoint, Geopoint, boolean, boolean)} with * <code>showInternalMap = true</code> and <code>showDefaultNavigation = false</code> * * @param geo @@ -89,7 +88,7 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @param waypoint * @param destination */ - public static void showNavigationMenu(final cgGeo geo, final Activity activity, + public static void showNavigationMenu(final IGeoData geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint destination) { showNavigationMenu(geo, activity, cache, waypoint, destination, true, false); } @@ -111,9 +110,9 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @param showDefaultNavigation * should be <code>false</code> by default * - * @see #showNavigationMenu(cgGeo, Activity, cgCache, cgWaypoint, Geopoint) + * @see #showNavigationMenu(IGeoData, Activity, cgCache, cgWaypoint, Geopoint) */ - public static void showNavigationMenu(final cgGeo geo, final Activity activity, + public static void showNavigationMenu(final IGeoData geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint destination, final boolean showInternalMap, final boolean showDefaultNavigation) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); @@ -188,10 +187,10 @@ public final class NavigationAppFactory extends AbstractAppFactory { /** * Adds the installed navigation tools to the given menu. - * Use {@link #onMenuItemSelected(MenuItem, cgGeo, Activity, cgCache, SearchResult, cgWaypoint, Geopoint)} on + * Use {@link #onMenuItemSelected(MenuItem, IGeoData, Activity, cgCache, cgWaypoint, Geopoint)} on * selection event to start the selected navigation tool. * - * <b>Only use this way if {@link #showNavigationMenu(cgGeo, Activity, cgCache, SearchResult, cgWaypoint, Geopoint)} + * <b>Only use this way if {@link #showNavigationMenu(IGeoData, Activity, cgCache, cgWaypoint, Geopoint)} * is not suitable for the given usecase.</b> * * @param menu @@ -203,11 +202,11 @@ public final class NavigationAppFactory extends AbstractAppFactory { /** * Adds the installed navigation tools to the given menu. - * Use {@link #onMenuItemSelected(MenuItem, cgGeo, Activity, cgCache, cgWaypoint, Geopoint)} on + * Use {@link #onMenuItemSelected(MenuItem, IGeoData, Activity, cgCache, cgWaypoint, Geopoint)} on * selection event to start the selected navigation tool. * * <b>Only use this way if - * {@link #showNavigationMenu(cgGeo, Activity, cgCache, cgWaypoint, Geopoint, boolean, boolean)} is + * {@link #showNavigationMenu(IGeoData, Activity, cgCache, cgWaypoint, Geopoint, boolean, boolean)} is * not suitable for the given usecase.</b> * * @param menu @@ -239,7 +238,7 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @return */ public static boolean onMenuItemSelected(final MenuItem item, - final cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint destination) { + final IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint destination) { if (cache == null && waypoint == null && destination == null) { return false; } @@ -271,11 +270,10 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @param geo * @param activity * @param cache - * @param search * @param waypoint * @param destination */ - public static void startDefaultNavigationApplication(final cgGeo geo, Activity activity, cgCache cache, + public static void startDefaultNavigationApplication(final IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint destination) { final NavigationApp app = getDefaultNavigationApplication(activity); @@ -294,11 +292,10 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @param geo * @param activity * @param cache - * @param search * @param waypoint * @param destination */ - public static void startDefaultNavigationApplication2(final cgGeo geo, Activity activity, cgCache cache, + public static void startDefaultNavigationApplication2(final IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint destination) { final NavigationApp app = getDefaultNavigationApplication2(activity); diff --git a/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java b/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java index a87e61b..9af90ac 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java @@ -1,8 +1,8 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter.Format; @@ -21,7 +21,7 @@ class RMapsApp extends AbstractNavigationApp { } @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { try { final ArrayList<String> locations = new ArrayList<String>(); if (cache != null && cache.getCoords() != null) { diff --git a/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java b/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java index db316bd..d8b66c2 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java @@ -1,12 +1,12 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.ILogable; import cgeo.geocaching.R; import cgeo.geocaching.StaticMapsActivity; +import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; -import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; import android.app.Activity; @@ -25,7 +25,7 @@ class StaticMapApp extends AbstractNavigationApp { } @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { final ILogable logable = cache != null && cache.getListId() != 0 ? cache : waypoint; final String geocode = logable.getGeocode().toUpperCase(); if (geocode == null) { diff --git a/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java b/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java index 621aea4..45ebaff 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java +++ b/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java @@ -1,9 +1,9 @@ package cgeo.geocaching.apps.cachelist; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.apps.App; +import cgeo.geocaching.cgCache; import android.app.Activity; @@ -11,7 +11,7 @@ import java.util.List; interface CacheListApp extends App { - boolean invoke(final cgGeo geo, final List<cgCache> caches, + boolean invoke(final IGeoData geo, final List<cgCache> caches, final Activity activity, final SearchResult search); } diff --git a/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java b/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java index c8f201d..3c9d8df 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java +++ b/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java @@ -1,11 +1,11 @@ package cgeo.geocaching.apps.cachelist; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.activity.IAbstractActivity; import cgeo.geocaching.apps.AbstractAppFactory; +import cgeo.geocaching.cgCache; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.ArrayUtils; @@ -63,7 +63,7 @@ public final class CacheListAppFactory extends AbstractAppFactory { } public static boolean onMenuItemSelected(final MenuItem item, - final cgGeo geo, final List<cgCache> caches, final IAbstractActivity activity, + final IGeoData geo, final List<cgCache> caches, final IAbstractActivity activity, final SearchResult search) { CacheListApp app = (CacheListApp) getAppFromMenuItem(item, apps); if (app != null) { diff --git a/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java b/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java index 5eaefc9..f450bbc 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java +++ b/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java @@ -1,10 +1,10 @@ package cgeo.geocaching.apps.cachelist; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.apps.AbstractApp; +import cgeo.geocaching.cgCache; import cgeo.geocaching.maps.CGeoMap; import android.app.Activity; @@ -24,7 +24,7 @@ class InternalCacheListMap extends AbstractApp implements CacheListApp { } @Override - public boolean invoke(cgGeo geo, List<cgCache> caches, Activity activity, final SearchResult search) { + public boolean invoke(IGeoData geo, List<cgCache> caches, Activity activity, final SearchResult search) { CGeoMap.startActivitySearch(activity, search, null); return true; } diff --git a/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java b/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java index 1b50861..b7557c3 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java +++ b/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java @@ -1,10 +1,10 @@ package cgeo.geocaching.apps.cachelist; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.apps.AbstractLocusApp; +import cgeo.geocaching.cgCache; import org.apache.commons.collections.CollectionUtils; @@ -29,7 +29,7 @@ class LocusCacheListApp extends AbstractLocusApp implements CacheListApp { * @author koem */ @Override - public boolean invoke(cgGeo geo, List<cgCache> cacheList, Activity activity, final SearchResult search) { + public boolean invoke(IGeoData geo, List<cgCache> cacheList, Activity activity, final SearchResult search) { if (CollectionUtils.isEmpty(cacheList)) { return false; } diff --git a/main/src/cgeo/geocaching/cgGeo.java b/main/src/cgeo/geocaching/cgGeo.java deleted file mode 100644 index c5ab556..0000000 --- a/main/src/cgeo/geocaching/cgGeo.java +++ /dev/null @@ -1,252 +0,0 @@ -package cgeo.geocaching; - -import cgeo.geocaching.enumerations.LocationProviderType; -import cgeo.geocaching.geopoint.Geopoint; -import cgeo.geocaching.go4cache.Go4Cache; -import cgeo.geocaching.utils.Log; - -import android.content.Context; -import android.location.GpsSatellite; -import android.location.GpsStatus; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.os.Bundle; - -import java.util.Iterator; - -public class cgGeo { - - private static final String LAST_LOCATION_PSEUDO_PROVIDER = "last"; - private final LocationManager geoManager = (LocationManager) cgeoapplication.getInstance().getSystemService(Context.LOCATION_SERVICE); - private UpdateLocationCallback updateLocationCallback = null; - private final AbstractLocationListener networkListener = new NetworkLocationListener(); - private final AbstractLocationListener gpsListener = new GpsLocationListener(); - private final GpsStatusListener gpsStatusListener = new GpsStatusListener(); - private Location locGps = null; - private Location locNet = null; - private long locGpsLast = 0L; - public Location location = null; - public LocationProviderType locationProvider = LocationProviderType.LAST; - public Geopoint coordsNow = null; - public Double altitudeNow = null; - public float bearingNow = 0; - public float speedNow = 0; - public float accuracyNow = -1f; - public int satellitesVisible = 0; - public int satellitesFixed = 0; - - public cgGeo() { - restoreLastLocation(); - - geoManager.addGpsStatusListener(gpsStatusListener); - - for (AbstractLocationListener listener : new AbstractLocationListener[] { networkListener, gpsListener }) { - try { - geoManager.requestLocationUpdates(listener.locationProvider, 0, 0, listener); - } catch (Exception e) { - Log.w("There is no location provider " + listener.locationProvider); - } - } - } - - public void closeGeo() { - geoManager.removeUpdates(networkListener); - geoManager.removeUpdates(gpsListener); - geoManager.removeGpsStatusListener(gpsStatusListener); - } - - public void replaceUpdate(UpdateLocationCallback callback) { - updateLocationCallback = callback; - fireLocationCallback(); - } - - private void fireLocationCallback() { - if (updateLocationCallback != null) { - updateLocationCallback.updateLocation(this); - } - } - - private static abstract class AbstractLocationListener implements LocationListener { - private final String locationProvider; - - protected AbstractLocationListener(String provider) { - this.locationProvider = provider; - } - - @Override - public void onStatusChanged(String provider, int status, Bundle extras) { - // nothing - } - - @Override - public void onProviderDisabled(String provider) { - // nothing - } - - @Override - public void onProviderEnabled(String provider) { - // nothing - } - } - - private final class GpsLocationListener extends AbstractLocationListener { - - public GpsLocationListener() { - super(LocationManager.GPS_PROVIDER); - } - - @Override - public void onLocationChanged(Location location) { - locGps = location; - locGpsLast = System.currentTimeMillis(); - selectBest(location.getProvider()); - } - } - - private final class NetworkLocationListener extends AbstractLocationListener { - - protected NetworkLocationListener() { - super(LocationManager.NETWORK_PROVIDER); - } - - @Override - public void onLocationChanged(Location location) { - locNet = location; - selectBest(location.getProvider()); - } - - } - - private final class GpsStatusListener implements GpsStatus.Listener { - - @Override - public void onGpsStatusChanged(int event) { - if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) { - final GpsStatus status = geoManager.getGpsStatus(null); - final Iterator<GpsSatellite> statusIterator = status.getSatellites().iterator(); - - int satellites = 0; - int fixed = 0; - - while (statusIterator.hasNext()) { - GpsSatellite sat = statusIterator.next(); - if (sat.usedInFix()) { - fixed++; - } - satellites++; - } - - boolean changed = false; - if (satellites != satellitesVisible) { - satellitesVisible = satellites; - changed = true; - } - if (fixed != satellitesFixed) { - satellitesFixed = fixed; - changed = true; - } - - if (changed) { - selectBest(null); - } - } - } - } - - private void selectBest(final String signallingProvider) { - if (locNet != null && locGps == null) { // we have only NET - assign(locNet); - } - else if ((locNet == null && locGps != null) // we have only GPS - || (satellitesFixed > 0) // GPS seems to be fixed - || (signallingProvider != null && signallingProvider.equals(LocationManager.GPS_PROVIDER)) // we have new location from GPS - || locGpsLast > (System.currentTimeMillis() - 30 * 1000) // GPS was working in last 30 seconds - ) { - assign(locGps); - } - else { - assign(locNet); // nothing else, using NET - } - } - - private void assignLastLocation(final Geopoint coords) { - if (coords == null) { - return; - } - - locationProvider = LocationProviderType.LAST; - coordsNow = coords; - altitudeNow = null; - bearingNow = 0f; - speedNow = 0f; - accuracyNow = 999f; - - fireLocationCallback(); - } - - private void assign(final Location loc) { - if (loc == null) { - locationProvider = LocationProviderType.LAST; - return; - } - - location = loc; - - final String provider = location.getProvider(); - if (provider.equals(LocationManager.GPS_PROVIDER)) { - locationProvider = LocationProviderType.GPS; - } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) { - locationProvider = LocationProviderType.NETWORK; - } else if (provider.equalsIgnoreCase(LAST_LOCATION_PSEUDO_PROVIDER)) { - locationProvider = LocationProviderType.LAST; - } - - coordsNow = new Geopoint(location.getLatitude(), location.getLongitude()); - cgeoapplication.getInstance().setLastCoords(coordsNow); - - if (location.hasAltitude() && locationProvider != LocationProviderType.LAST) { - altitudeNow = location.getAltitude() + Settings.getAltCorrection(); - } else { - altitudeNow = null; - } - if (location.hasBearing() && locationProvider != LocationProviderType.LAST) { - bearingNow = location.getBearing(); - } else { - bearingNow = 0f; - } - if (location.hasSpeed() && locationProvider != LocationProviderType.LAST) { - speedNow = location.getSpeed(); - } else { - speedNow = 0f; - } - if (location.hasAccuracy() && locationProvider != LocationProviderType.LAST) { - accuracyNow = location.getAccuracy(); - } else { - accuracyNow = 999f; - } - - fireLocationCallback(); - - if (locationProvider == LocationProviderType.GPS || locationProvider == LocationProviderType.NETWORK) { - Go4Cache.signalCoordinates(coordsNow); - } - } - - private void restoreLastLocation() { - // restore from last location (stored by app) - assignLastLocation(cgeoapplication.getInstance().getLastCoords()); - - // restore from last location (stored by device sensors) - for (String provider : new String[] { LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER }) { - final Location lastLocation = geoManager.getLastKnownLocation(provider); - if (lastLocation != null) { - lastLocation.setProvider(LAST_LOCATION_PSEUDO_PROVIDER); - assign(lastLocation); - - Log.i("Using last location from " + provider); - break; - } - } - } -} diff --git a/main/src/cgeo/geocaching/cgeo.java b/main/src/cgeo/geocaching/cgeo.java index 7ae235b..1d266e6 100644 --- a/main/src/cgeo/geocaching/cgeo.java +++ b/main/src/cgeo/geocaching/cgeo.java @@ -22,6 +22,7 @@ import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.location.Address; @@ -58,7 +59,6 @@ public class cgeo extends AbstractActivity { public static final int SEARCH_REQUEST_CODE = 2; private int version = 0; - private cgGeo geo = null; private TextView filterTitle = null; private boolean cleanupRunning = false; private int countBubbleCnt = 0; @@ -68,6 +68,7 @@ public class cgeo extends AbstractActivity { private boolean initialized = false; private LocationManager locationManager; + final private UpdateLocation locationUpdater = new UpdateLocation(); private boolean gpsEnabled = false; private Handler updateUserInfoHandler = new Handler() { @@ -115,9 +116,7 @@ public class cgeo extends AbstractActivity { addText.append(address.getAdminArea()); } - if (geo != null) { - addCoords = geo.coordsNow; - } + addCoords = app.currentGeo().getCoordsNow(); TextView navLocation = (TextView) findViewById(R.id.nav_location); navLocation.setText(addText.toString()); @@ -209,29 +208,22 @@ public class cgeo extends AbstractActivity { app.setAction(null); - app.cleanGeo(); app.cleanDir(); setContentView(R.layout.main); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); // type to search try { - PackageManager manager = this.getPackageManager(); - PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); - + final PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), 0); version = info.versionCode; - - Log.i("Starting " + info.packageName + " " + info.versionCode + " a.k.a " + info.versionName + "..."); - - info = null; - manager = null; - } catch (Exception e) { + Log.i("Starting " + info.packageName + " " + info.versionCode + " a.k.a " + info.versionName + "…"); + } catch (final NameNotFoundException e) { Log.i("No info."); } try { if (!Settings.isHelpShown()) { - RelativeLayout helper = (RelativeLayout) findViewById(R.id.helper); + final RelativeLayout helper = (RelativeLayout) findViewById(R.id.helper); if (helper != null) { helper.setVisibility(View.VISIBLE); helper.setClickable(true); @@ -264,12 +256,10 @@ public class cgeo extends AbstractActivity { @Override public void onResume() { super.onResume(); - + app.addGeoObserver(locationUpdater); gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); locationManager.addGpsStatusListener(gpsListener); - updateUserInfoHandler.sendEmptyMessage(-1); - init(); } @@ -278,34 +268,20 @@ public class cgeo extends AbstractActivity { initialized = false; app.showLoginToast = true; - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { initialized = false; - - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { initialized = false; - + app.deleteGeoObserver(locationUpdater); locationManager.removeGpsStatusListener(gpsListener); - - if (geo != null) { - geo = app.removeGeo(); - } - super.onPause(); } @@ -518,10 +494,6 @@ public class cgeo extends AbstractActivity { (new firstLogin()).start(); } - if (geo == null) { - geo = app.startGeo(new UpdateLocation()); - } - final View findOnMap = findViewById(R.id.map); findOnMap.setClickable(true); findOnMap.setOnClickListener(new OnClickListener() { @@ -601,21 +573,16 @@ public class cgeo extends AbstractActivity { .show(); } - private class UpdateLocation implements UpdateLocationCallback { - - private final View nearestView = findViewById(R.id.nearest); - private final TextView navType = (TextView) findViewById(R.id.nav_type); - private final TextView navAccuracy = (TextView) findViewById(R.id.nav_accuracy); - private final TextView navLocation = (TextView) findViewById(R.id.nav_location); + private class UpdateLocation extends GeoObserver { @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - + public void updateLocation(final IGeoData geo) { + final View nearestView = findViewById(R.id.nearest); + final TextView navType = (TextView) findViewById(R.id.nav_type); + final TextView navAccuracy = (TextView) findViewById(R.id.nav_accuracy); + final TextView navLocation = (TextView) findViewById(R.id.nav_location); try { - if (geo.coordsNow != null) { + if (geo.getCoordsNow() != null) { if (!nearestView.isClickable()) { nearestView.setFocusable(true); nearestView.setClickable(true); @@ -630,17 +597,17 @@ public class cgeo extends AbstractActivity { if (!gpsEnabled) { satellitesHandler.noGps(); } else { - satellitesHandler.satellites(geo.satellitesFixed, geo.satellitesVisible); + satellitesHandler.satellites(geo.getSatellitesFixed(), geo.getSatellitesVisible()); } - navType.setText(res.getString(geo.locationProvider.resourceId)); + navType.setText(res.getString(geo.getLocationProvider().resourceId)); - if (geo.accuracyNow >= 0) { - int speed = Math.round(geo.speedNow) * 60 * 60 / 1000; + if (geo.getAccuracyNow() >= 0) { + int speed = Math.round(geo.getSpeedNow()) * 60 * 60 / 1000; if (Settings.isUseMetricUnits()) { - navAccuracy.setText("±" + Math.round(geo.accuracyNow) + " m" + Formatter.SEPARATOR + speed + " km/h"); + navAccuracy.setText("±" + Math.round(geo.getAccuracyNow()) + " m" + Formatter.SEPARATOR + speed + " km/h"); } else { - navAccuracy.setText("±" + Math.round(geo.accuracyNow * IConversion.METERS_TO_FEET) + " ft" + Formatter.SEPARATOR + speed / IConversion.MILES_TO_KILOMETER + " mph"); + navAccuracy.setText("±" + Math.round(geo.getAccuracyNow() * IConversion.METERS_TO_FEET) + " ft" + Formatter.SEPARATOR + speed / IConversion.MILES_TO_KILOMETER + " mph"); } } else { navAccuracy.setText(null); @@ -650,15 +617,15 @@ public class cgeo extends AbstractActivity { if (addCoords == null) { navLocation.setText(res.getString(R.string.loc_no_addr)); } - if (addCoords == null || (geo.coordsNow.distanceTo(addCoords) > 0.5 && !addressObtaining)) { + if (addCoords == null || (geo.getCoordsNow().distanceTo(addCoords) > 0.5 && !addressObtaining)) { (new ObtainAddressThread()).start(); } } else { - if (geo.altitudeNow != null) { - final String humanAlt = HumanDistance.getHumanDistance(geo.altitudeNow.floatValue() / 1000); - navLocation.setText(geo.coordsNow + " | " + humanAlt); + if (geo.getAltitudeNow() != null) { + final String humanAlt = HumanDistance.getHumanDistance(geo.getAltitudeNow().floatValue() / 1000); + navLocation.setText(geo.getCoordsNow() + " | " + humanAlt); } else { - navLocation.setText(geo.coordsNow.toString()); + navLocation.setText(geo.getCoordsNow().toString()); } } } else { @@ -692,12 +659,12 @@ public class cgeo extends AbstractActivity { * unused here but needed since this method is referenced from XML layout */ public void cgeoFindNearest(View v) { - if (geo == null || geo.coordsNow == null) { + if (app.currentGeo().getCoordsNow() == null) { return; } findViewById(R.id.nearest).setPressed(true); - cgeocaches.startActivityNearest(this, geo.coordsNow); + cgeocaches.startActivityNearest(this, app.currentGeo().getCoordsNow()); } /** @@ -859,9 +826,6 @@ public class cgeo extends AbstractActivity { @Override public void run() { - if (geo == null) { - return; - } if (addressObtaining) { return; } @@ -869,8 +833,8 @@ public class cgeo extends AbstractActivity { try { final Geocoder geocoder = new Geocoder(cgeo.this, Locale.getDefault()); - - addresses = geocoder.getFromLocation(geo.coordsNow.getLatitude(), geo.coordsNow.getLongitude(), 1); + final Geopoint coords = app.currentGeo().getCoordsNow(); + addresses = geocoder.getFromLocation(coords.getLatitude(), coords.getLongitude(), 1); } catch (Exception e) { Log.i("Failed to obtain address"); } diff --git a/main/src/cgeo/geocaching/cgeoadvsearch.java b/main/src/cgeo/geocaching/cgeoadvsearch.java index 4da0437..46c97be 100644 --- a/main/src/cgeo/geocaching/cgeoadvsearch.java +++ b/main/src/cgeo/geocaching/cgeoadvsearch.java @@ -6,6 +6,7 @@ import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.utils.BaseUtils; import cgeo.geocaching.utils.EditUtils; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; @@ -23,13 +24,11 @@ import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; -public class cgeoadvsearch extends AbstractActivity { +public class cgeoadvsearch extends AbstractActivity implements IObserver<IGeoData> { public static final String EXTRAS_KEYWORDSEARCH = "keywordsearch"; private static final int MENU_SEARCH_OWN_CACHES = 1; - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); private EditText latEdit = null; private EditText lonEdit = null; @@ -78,34 +77,23 @@ public class cgeoadvsearch extends AbstractActivity { @Override public void onResume() { super.onResume(); - + app.addGeoObserver(this); init(); } @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(this); super.onPause(); } @@ -146,10 +134,6 @@ public class cgeoadvsearch extends AbstractActivity { private void init() { Settings.getLogin(); - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - ((Button) findViewById(R.id.buttonLatitude)).setOnClickListener(new findByCoordsAction()); ((Button) findViewById(R.id.buttonLongitude)).setOnClickListener(new findByCoordsAction()); @@ -237,33 +221,26 @@ public class cgeoadvsearch extends AbstractActivity { displayTrackable.setOnClickListener(new findTrackableListener()); } - private class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; + @Override + public void update(final IGeoData geo) { + try { + if (latEdit == null) { + latEdit = (EditText) findViewById(R.id.latitude); + } + if (lonEdit == null) { + lonEdit = (EditText) findViewById(R.id.longitude); } - try { - if (latEdit == null) { - latEdit = (EditText) findViewById(R.id.latitude); + if (geo.getCoordsNow() != null) { + if (latEdit != null) { + latEdit.setHint(geo.getCoordsNow().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); } - if (lonEdit == null) { - lonEdit = (EditText) findViewById(R.id.longitude); - } - - if (geo.coordsNow != null) { - if (latEdit != null) { - latEdit.setHint(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); - } - if (lonEdit != null) { - lonEdit.setHint(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); - } + if (lonEdit != null) { + lonEdit.setHint(geo.getCoordsNow().format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); } - } catch (Exception e) { - Log.w("Failed to update location."); } + } catch (Exception e) { + Log.w("Failed to update location."); } } @@ -271,7 +248,7 @@ public class cgeoadvsearch extends AbstractActivity { @Override public void onClick(View arg0) { - cgeocoords coordsDialog = new cgeocoords(cgeoadvsearch.this, null, null, geo); + cgeocoords coordsDialog = new cgeocoords(cgeoadvsearch.this, null, null, app.currentGeo()); coordsDialog.setCancelable(true); coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() { @Override @@ -298,9 +275,10 @@ public class cgeoadvsearch extends AbstractActivity { final String lonText = lonView.getText().toString(); if (StringUtils.isEmpty(latText) || StringUtils.isEmpty(lonText)) { - if (geo.coordsNow != null) { - latView.setText(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE)); - lonView.setText(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE)); + final IGeoData geo = app.currentGeo(); + if (geo.getCoordsNow() != null) { + latView.setText(geo.getCoordsNow().format(GeopointFormatter.Format.LAT_DECMINUTE)); + lonView.setText(geo.getCoordsNow().format(GeopointFormatter.Format.LON_DECMINUTE)); } } else { try { diff --git a/main/src/cgeo/geocaching/cgeoapplication.java b/main/src/cgeo/geocaching/cgeoapplication.java index 2b10c16..7cd67bb 100644 --- a/main/src/cgeo/geocaching/cgeoapplication.java +++ b/main/src/cgeo/geocaching/cgeoapplication.java @@ -9,6 +9,7 @@ import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.utils.Log; +import cgeo.geocaching.utils.IObserver; import org.apache.commons.lang3.StringUtils; @@ -34,8 +35,7 @@ public class cgeoapplication extends Application { private cgData storage = null; private String action = null; private Geopoint lastCoords = null; - private cgGeo geo = null; - private boolean geoInUse = false; + private GeoDataProvider geo; private cgDirection dir = null; private boolean dirInUse = false; public boolean firstRun = true; // c:geo is just launched @@ -63,7 +63,6 @@ public class cgeoapplication extends Application { public void onTerminate() { Log.d("Terminating c:geo..."); - cleanGeo(); cleanDir(); if (storage != null) { @@ -114,66 +113,38 @@ public class cgeoapplication extends Application { restoreThread.start(); } - public void cleanGeo() { - if (geo != null) { - geo.closeGeo(); - geo = null; - } + public void addGeoObserver(final IObserver<? super IGeoData> observer) { + currentGeoObject().addObserver(observer); } - public void cleanDir() { - if (dir != null) { - dir.closeDir(); - dir = null; - } - } - - public boolean storageStatus() { - return storage.status(); + public void deleteGeoObserver(final IObserver<? super IGeoData> observer) { + currentGeoObject().deleteObserver(observer); } - public cgGeo startGeo(UpdateLocationCallback geoUpdate) { + private GeoDataProvider currentGeoObject() { if (geo == null) { - geo = new cgGeo(); - Log.i("Location service started"); + synchronized(this) { + if (geo == null) { + geo = new GeoDataProvider(this); + } + } } - - geo.replaceUpdate(geoUpdate); - geoInUse = true; - return geo; } - public float getSpeedFromGeo() { - return geo != null ? geo.speedNow : 0f; + public IGeoData currentGeo() { + return currentGeoObject().getMemory(); } - public cgGeo removeGeo() { - if (geo != null) { - geo.replaceUpdate(null); + public void cleanDir() { + if (dir != null) { + dir.closeDir(); + dir = null; } - geoInUse = false; - - (new removeGeoThread()).start(); - - return null; } - private class removeGeoThread extends Thread { - - @Override - public void run() { - try { - sleep(2500); - } catch (Exception e) { - // nothing - } - - if (!geoInUse && geo != null) { - cleanGeo(); - Log.i("Location service stopped"); - } - } + public boolean storageStatus() { + return storage.status(); } public cgDirection startDir(Context context, UpdateDirectionCallback dirUpdate) { @@ -264,10 +235,7 @@ public class cgeoapplication extends Application { return null; } - cgTrackable trackable = null; - trackable = storage.loadTrackable(geocode); - - return trackable; + return storage.loadTrackable(geocode); } /** {@link cgData#allDetailedThere()} */ @@ -304,24 +272,24 @@ public class cgeoapplication extends Application { return new SearchResult(geocodes, getAllHistoricCachesCount()); } - /** {@link cgData#loadCachedInViewport(long, long, long, long, CacheType)} */ + /** {@link cgData#loadCachedInViewport(Viewport, CacheType)} */ public SearchResult getCachedInViewport(final Viewport viewport, final CacheType cacheType) { final Set<String> geocodes = storage.loadCachedInViewport(viewport, cacheType); return new SearchResult(geocodes); } - /** {@link cgData#loadStoredInViewport(long, long, long, long, CacheType)} */ + /** {@link cgData#loadStoredInViewport(Viewport, CacheType)} */ public SearchResult getStoredInViewport(final Viewport viewport, final CacheType cacheType) { final Set<String> geocodes = storage.loadStoredInViewport(viewport, cacheType); return new SearchResult(geocodes); } - /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, Integer)} */ + /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, int)} */ public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType) { return storage.getAllStoredCachesCount(detailedOnly, cacheType, 0); } - /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, Integer)} */ + /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, int)} */ public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType, final Integer list) { return storage.getAllStoredCachesCount(detailedOnly, cacheType, list); } diff --git a/main/src/cgeo/geocaching/cgeocaches.java b/main/src/cgeo/geocaching/cgeocaches.java index 6e62e09..8990e22 100644 --- a/main/src/cgeo/geocaching/cgeocaches.java +++ b/main/src/cgeo/geocaching/cgeocaches.java @@ -38,6 +38,7 @@ import cgeo.geocaching.sorting.VisitComparator; import cgeo.geocaching.sorting.VoteComparator; import cgeo.geocaching.ui.CacheListAdapter; import cgeo.geocaching.utils.Log; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.RunnableWithArgument; import org.apache.commons.collections.CollectionUtils; @@ -74,7 +75,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -public class cgeocaches extends AbstractListActivity { +public class cgeocaches extends AbstractListActivity implements IObserver<IGeoData> { private static final int MAX_LIST_ITEMS = 1000; private static final String EXTRAS_LIST_TYPE = "type"; @@ -120,6 +121,7 @@ public class cgeocaches extends AbstractListActivity { private static final int MENU_FILTER = 74; private static final int MSG_DONE = -1; + private static final int MSG_RESTART_GEO_AND_DIR = -2; private static final int MSG_CANCEL = -99; private String action = null; @@ -137,9 +139,7 @@ public class cgeocaches extends AbstractListActivity { private TextView listFooterText = null; private Progress progress = new Progress(); private Float northHeading = 0f; - private cgGeo geo = null; private cgDirection dir = null; - private UpdateLocationCallback geoUpdate = new UpdateLocation(); private UpdateDirectionCallback dirUpdate = new UpdateDirection(); private String title = ""; private int detailTotal = 0; @@ -210,8 +210,9 @@ public class cgeocaches extends AbstractListActivity { return; } - if (geo != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); + final Geopoint coordsNow = app.currentGeo().getCoordsNow(); + if (coordsNow != null) { + adapter.setActualCoordinates(coordsNow); adapter.setActualHeading(northHeading); } } catch (Exception e) { @@ -277,8 +278,9 @@ public class cgeocaches extends AbstractListActivity { return; } - if (geo != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); + final Geopoint coordsNow = app.currentGeo().getCoordsNow(); + if (coordsNow != null) { + adapter.setActualCoordinates(coordsNow); adapter.setActualHeading(northHeading); } } catch (Exception e) { @@ -322,6 +324,8 @@ public class cgeocaches extends AbstractListActivity { if (threadDetails != null) { threadDetails.kill(); } + } else if (msg.what == MSG_RESTART_GEO_AND_DIR) { + startGeoAndDir(); } else { if (cacheList != null && search != null) { final Set<cgCache> cacheListTmp = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB); @@ -333,8 +337,9 @@ public class cgeocaches extends AbstractListActivity { } } - if (geo != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); + final Geopoint coordsNow = app.currentGeo().getCoordsNow(); + if (coordsNow != null) { + adapter.setActualCoordinates(coordsNow); adapter.setActualHeading(northHeading); } @@ -363,12 +368,10 @@ public class cgeocaches extends AbstractListActivity { refreshCurrentList(); } else if (msg.what == -2) { progress.dismiss(); - startGeoAndDir(); showToast(res.getString(R.string.sendToCgeo_download_fail)); finish(); } else if (msg.what == -3) { progress.dismiss(); - startGeoAndDir(); showToast(res.getString(R.string.sendToCgeo_no_registration)); finish(); } else if (msg.what == MSG_CANCEL) { @@ -390,7 +393,6 @@ public class cgeocaches extends AbstractListActivity { Collections.sort(cacheList, gcComparator); } - startGeoAndDir(); progress.dismiss(); } } @@ -469,6 +471,13 @@ public class cgeocaches extends AbstractListActivity { super.onCreate(savedInstanceState); // init + if (CollectionUtils.isNotEmpty(cacheList)) { + setMoreCaches(); + } + + setTitle(title); + setAdapter(); + app.setAction(action); setTheme(); @@ -493,8 +502,6 @@ public class cgeocaches extends AbstractListActivity { } } - init(); - Thread threadPure; cgSearchThread thread; @@ -641,8 +648,6 @@ public class cgeocaches extends AbstractListActivity { @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); - - init(); } @Override @@ -651,15 +656,13 @@ public class cgeocaches extends AbstractListActivity { init(); - if (adapter != null && geo != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); - adapter.setActualHeading(northHeading); - } - if (adapter != null) { adapter.setSelectMode(false, true); - if (geo != null && geo.coordsNow != null) { - adapter.forceSort(geo.coordsNow); + final Geopoint coordsNow = app.currentGeo().getCoordsNow(); + if (coordsNow != null) { + adapter.setActualCoordinates(coordsNow); + adapter.setActualHeading(northHeading); + adapter.forceSort(coordsNow); } } @@ -682,15 +685,11 @@ public class cgeocaches extends AbstractListActivity { adapter = null; } - removeGeoAndDir(); - super.onDestroy(); } @Override public void onStop() { - removeGeoAndDir(); - super.onStop(); } @@ -983,7 +982,7 @@ public class cgeocaches extends AbstractListActivity { return true; } - return CacheListAppFactory.onMenuItemSelected(item, geo, cacheList, this, search); + return CacheListAppFactory.onMenuItemSelected(item, app.currentGeo(), cacheList, this, search); } private void setComparator(MenuItem item, @@ -1050,8 +1049,7 @@ public class cgeocaches extends AbstractListActivity { final boolean moveAll = adapter.getChecked() == 0; if (moveAll) { selected = new ArrayList<cgCache>(cacheList); - } - else { + } else { selected = adapter.getCheckedCaches(); } app.moveToList(selected, newListId); @@ -1083,11 +1081,11 @@ public class cgeocaches extends AbstractListActivity { if (id == MENU_DEFAULT_NAVIGATION) { final cgCache cache = getCacheFromAdapter(adapterInfo); - NavigationAppFactory.startDefaultNavigationApplication(geo, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, cache, null, null); return true; } else if (id == MENU_NAVIGATION) { final cgCache cache = getCacheFromAdapter(adapterInfo); - NavigationAppFactory.showNavigationMenu(geo, this, cache, null, null); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, cache, null, null); return true; } else if (id == MENU_LOG_VISIT) { getCacheFromAdapter(adapterInfo).logVisit(this); @@ -1211,9 +1209,8 @@ public class cgeocaches extends AbstractListActivity { } adapter.reFilter(); - if (geo != null) { - adapter.setActualCoordinates(geo.coordsNow); - } + adapter.setActualCoordinates(app.currentGeo().getCoordsNow()); + if (dir != null) { adapter.setActualHeading(dir.directionNow); } @@ -1263,38 +1260,22 @@ public class cgeocaches extends AbstractListActivity { private void init() { startGeoAndDir(); - if (CollectionUtils.isNotEmpty(cacheList)) { - setMoreCaches(); - } - - setTitle(title); - setAdapter(); - - if (geo != null) { - geoUpdate.updateLocation(geo); - } if (dir != null) { dirUpdate.updateDirection(dir); } } - // sensor & geolocation manager + // Sensor & geolocation manager. This must be called from the UI thread as it may + // cause the system listeners to start if nobody else required them before. private void startGeoAndDir() { - if (geo == null) { - geo = app.startGeo(geoUpdate); - } + app.addGeoObserver(this); if (Settings.isLiveList() && Settings.isUseCompass() && dir == null) { dir = app.startDir(this, dirUpdate); } } private void removeGeoAndDir() { - if (dir != null) { - dir = app.removeDir(); - } - if (geo != null) { - geo = app.removeGeo(); - } + app.deleteGeoObserver(this); } private void importGpx() { @@ -1442,33 +1423,27 @@ public class cgeocaches extends AbstractListActivity { threadR.start(); } - private class UpdateLocation implements UpdateLocationCallback { + @Override + public void update(final IGeoData geo) { + if (adapter == null) { + return; + } - @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - if (adapter == null) { - return; + try { + if (cacheList != null && geo.getCoordsNow() != null) { + adapter.setActualCoordinates(geo.getCoordsNow()); } - try { - if (cacheList != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); + if (!Settings.isUseCompass() || geo.getSpeedNow() > 5) { // use GPS when speed is higher than 18 km/h + if (!Settings.isUseCompass()) { + adapter.setActualHeading(geo.getBearingNow()); } - - if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h - if (!Settings.isUseCompass()) { - adapter.setActualHeading(geo.bearingNow); - } - if (northHeading != null) { - adapter.setActualHeading(northHeading); - } + if (northHeading != null) { + adapter.setActualHeading(northHeading); } - } catch (Exception e) { - Log.w("Failed to UpdateLocation location."); } + } catch (Exception e) { + Log.w("Failed to UpdateLocation location."); } } @@ -1484,7 +1459,7 @@ public class cgeocaches extends AbstractListActivity { } northHeading = dir.directionNow; - if (northHeading != null && adapter != null && (geo == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h) { + if (northHeading != null && adapter != null && (app.currentGeo().getSpeedNow() <= 5)) { // use compass when speed is lower than 18 km/h) { adapter.setActualHeading(northHeading); } } @@ -1725,6 +1700,7 @@ public class cgeocaches extends AbstractListActivity { } cacheListTemp.clear(); + handler.sendEmptyMessage(MSG_RESTART_GEO_AND_DIR); handler.sendEmptyMessage(MSG_DONE); } } @@ -1810,6 +1786,8 @@ public class cgeocaches extends AbstractListActivity { } handler.sendEmptyMessage(ret); + + startGeoAndDir(); } } @@ -1837,6 +1815,8 @@ public class cgeocaches extends AbstractListActivity { removeGeoAndDir(); app.markDropped(selected); handler.sendEmptyMessage(MSG_DONE); + + startGeoAndDir(); } } diff --git a/main/src/cgeo/geocaching/cgeocoords.java b/main/src/cgeo/geocaching/cgeocoords.java index 57fd144..d6c923f 100644 --- a/main/src/cgeo/geocaching/cgeocoords.java +++ b/main/src/cgeo/geocaching/cgeocoords.java @@ -31,7 +31,7 @@ import android.widget.TextView; public class cgeocoords extends Dialog { final private AbstractActivity context; - final private cgGeo geo; + final private IGeoData geo; final private cgCache cache; private Geopoint gp; @@ -46,7 +46,7 @@ public class cgeocoords extends Dialog { private coordInputFormatEnum currentFormat = null; - public cgeocoords(final AbstractActivity context, final cgCache cache, final Geopoint gp, final cgGeo geo) { + public cgeocoords(final AbstractActivity context, final cgCache cache, final Geopoint gp, final IGeoData geo) { super(context); this.context = context; this.geo = geo; @@ -54,8 +54,8 @@ public class cgeocoords extends Dialog { if (gp != null) { this.gp = gp; - } else if (geo != null && geo.coordsNow != null) { - this.gp = geo.coordsNow; + } else if (geo != null && geo.getCoordsNow() != null) { + this.gp = geo.getCoordsNow(); } else { this.gp = new Geopoint(0.0, 0.0); } @@ -413,8 +413,8 @@ public class cgeocoords extends Dialog { // Start new format with an acceptable value: either the current one // entered by the user, else our current coordinates, else (0,0). if (!calc(false)) { - if (geo != null && geo.coordsNow != null) { - gp = geo.coordsNow; + if (geo != null && geo.getCoordsNow() != null) { + gp = geo.getCoordsNow(); } else { gp = new Geopoint(0.0, 0.0); } @@ -436,12 +436,12 @@ public class cgeocoords extends Dialog { @Override public void onClick(View v) { - if (geo == null || geo.coordsNow == null) { + if (geo == null || geo.getCoordsNow() == null) { context.showToast(context.getResources().getString(R.string.err_point_unknown_position)); return; } - gp = geo.coordsNow; + gp = geo.getCoordsNow(); updateGUI(); } } diff --git a/main/src/cgeo/geocaching/cgeonavigate.java b/main/src/cgeo/geocaching/cgeonavigate.java index 5f4a7f4..6c7e22b 100644 --- a/main/src/cgeo/geocaching/cgeonavigate.java +++ b/main/src/cgeo/geocaching/cgeonavigate.java @@ -7,6 +7,7 @@ import cgeo.geocaching.geopoint.IConversion; import cgeo.geocaching.maps.CGeoMap; import cgeo.geocaching.ui.CompassView; import cgeo.geocaching.utils.Log; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.PeriodicHandler; import org.apache.commons.lang3.StringUtils; @@ -24,7 +25,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -public class cgeonavigate extends AbstractActivity { +public class cgeonavigate extends AbstractActivity implements IObserver<IGeoData> { private static final String EXTRAS_COORDS = "coords"; private static final String EXTRAS_NAME = "name"; @@ -33,9 +34,7 @@ public class cgeonavigate extends AbstractActivity { private static final int MENU_MAP = 0; private static final int MENU_SWITCH_COMPASS_GPS = 1; private PowerManager pm = null; - private cgGeo geo = null; private cgDirection dir = null; - private UpdateLocationCallback geoUpdate = new update(); private UpdateDirectionCallback dirUpdate = new UpdateDirection(); private Geopoint dstCoords = null; private float cacheHeading = 0; @@ -74,9 +73,6 @@ public class cgeonavigate extends AbstractActivity { setTitle(res.getString(R.string.compass_title)); // sensor & geolocation manager - if (geo == null) { - geo = app.startGeo(geoUpdate); - } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(this, dirUpdate); } @@ -110,9 +106,6 @@ public class cgeonavigate extends AbstractActivity { setTitle(); setDestCoords(); - if (geo != null) { - geoUpdate.updateLocation(geo); - } if (dir != null) { dirUpdate.updateDirection(dir); } @@ -134,9 +127,7 @@ public class cgeonavigate extends AbstractActivity { setGo4CacheAction(); // sensor & geolocation manager - if (geo == null) { - geo = app.startGeo(geoUpdate); - } + app.addGeoObserver(this); if (Settings.isUseCompass() && dir == null) { dir = app.startDir(this, dirUpdate); } @@ -157,9 +148,6 @@ public class cgeonavigate extends AbstractActivity { @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } if (dir != null) { dir = app.removeDir(); } @@ -171,9 +159,7 @@ public class cgeonavigate extends AbstractActivity { @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } + app.deleteGeoObserver(this); if (dir != null) { dir = app.removeDir(); } @@ -183,9 +169,6 @@ public class cgeonavigate extends AbstractActivity { @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } if (dir != null) { dir = app.removeDir(); } @@ -253,7 +236,7 @@ public class cgeonavigate extends AbstractActivity { dstCoords = coordinate.getCoords(); setTitle(); setDestCoords(); - updateDistanceInfo(); + updateDistanceInfo(app.currentGeo()); Log.d("destination set: " + title + " (" + dstCoords + ")"); return true; @@ -278,8 +261,8 @@ public class cgeonavigate extends AbstractActivity { ((TextView) findViewById(R.id.destination)).setText(dstCoords.toString()); } - private void updateDistanceInfo() { - if (geo == null || geo.coordsNow == null || dstCoords == null) { + private void updateDistanceInfo(final IGeoData geo) { + if (geo.getCoordsNow() == null || dstCoords == null) { return; } @@ -290,69 +273,62 @@ public class cgeonavigate extends AbstractActivity { headingView = (TextView) findViewById(R.id.heading); } - cacheHeading = geo.coordsNow.bearingTo(dstCoords); - distanceView.setText(HumanDistance.getHumanDistance(geo.coordsNow.distanceTo(dstCoords))); + cacheHeading = geo.getCoordsNow().bearingTo(dstCoords); + distanceView.setText(HumanDistance.getHumanDistance(geo.getCoordsNow().distanceTo(dstCoords))); headingView.setText(Math.round(cacheHeading) + "°"); } - private class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; + @Override + public void update(final IGeoData geo) { + try { + if (navType == null || navLocation == null || navAccuracy == null) { + navType = (TextView) findViewById(R.id.nav_type); + navAccuracy = (TextView) findViewById(R.id.nav_accuracy); + navSatellites = (TextView) findViewById(R.id.nav_satellites); + navLocation = (TextView) findViewById(R.id.nav_location); } - try { - if (navType == null || navLocation == null || navAccuracy == null) { - navType = (TextView) findViewById(R.id.nav_type); - navAccuracy = (TextView) findViewById(R.id.nav_accuracy); - navSatellites = (TextView) findViewById(R.id.nav_satellites); - navLocation = (TextView) findViewById(R.id.nav_location); + if (geo.getCoordsNow() != null) { + String satellites = null; + if (geo.getSatellitesFixed() > 0) { + satellites = res.getString(R.string.loc_sat) + ": " + geo.getSatellitesFixed() + "/" + geo.getSatellitesVisible(); + } else if (geo.getSatellitesVisible() >= 0) { + satellites = res.getString(R.string.loc_sat) + ": 0/" + geo.getSatellitesVisible(); + } else { + satellites = ""; } + navSatellites.setText(satellites); + navType.setText(res.getString(geo.getLocationProvider().resourceId)); - if (geo.coordsNow != null) { - String satellites = null; - if (geo.satellitesFixed > 0) { - satellites = res.getString(R.string.loc_sat) + ": " + geo.satellitesFixed + "/" + geo.satellitesVisible; - } else if (geo.satellitesVisible >= 0) { - satellites = res.getString(R.string.loc_sat) + ": 0/" + geo.satellitesVisible; + if (geo.getAccuracyNow() >= 0) { + if (Settings.isUseMetricUnits()) { + navAccuracy.setText("±" + Math.round(geo.getAccuracyNow()) + " m"); } else { - satellites = ""; + navAccuracy.setText("±" + Math.round(geo.getAccuracyNow() * IConversion.METERS_TO_FEET) + " ft"); } - navSatellites.setText(satellites); - navType.setText(res.getString(geo.locationProvider.resourceId)); - - if (geo.accuracyNow >= 0) { - if (Settings.isUseMetricUnits()) { - navAccuracy.setText("±" + Math.round(geo.accuracyNow) + " m"); - } else { - navAccuracy.setText("±" + Math.round(geo.accuracyNow * IConversion.METERS_TO_FEET) + " ft"); - } - } else { - navAccuracy.setText(null); - } - - if (geo.altitudeNow != null) { - final String humanAlt = HumanDistance.getHumanDistance(geo.altitudeNow.floatValue() / 1000); - navLocation.setText(geo.coordsNow + " | " + humanAlt); - } else { - navLocation.setText(geo.coordsNow.toString()); - } - - updateDistanceInfo(); } else { - navType.setText(null); navAccuracy.setText(null); - navLocation.setText(res.getString(R.string.loc_trying)); } - if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h - northHeading = geo.bearingNow; + if (geo.getAltitudeNow() != null) { + final String humanAlt = HumanDistance.getHumanDistance(geo.getAltitudeNow().floatValue() / 1000); + navLocation.setText(geo.getCoordsNow() + " | " + humanAlt); + } else { + navLocation.setText(geo.getCoordsNow().toString()); } - } catch (Exception e) { - Log.w("Failed to update location."); + + updateDistanceInfo(geo); + } else { + navType.setText(null); + navAccuracy.setText(null); + navLocation.setText(res.getString(R.string.loc_trying)); + } + + if (!Settings.isUseCompass() || geo.getSpeedNow() > 5) { // use GPS when speed is higher than 18 km/h + northHeading = geo.getBearingNow(); } + } catch (Exception e) { + Log.w("Failed to LocationUpdater location."); } } @@ -364,7 +340,7 @@ public class cgeonavigate extends AbstractActivity { return; } - if (geo == null || geo.speedNow <= 5) { // use compass when speed is lower than 18 km/h + if (app.currentGeo().getSpeedNow() <= 5) { // use compass when speed is lower than 18 km/h northHeading = dir.directionNow; } } diff --git a/main/src/cgeo/geocaching/cgeopoint.java b/main/src/cgeo/geocaching/cgeopoint.java index f78d970..dc43e4a 100644 --- a/main/src/cgeo/geocaching/cgeopoint.java +++ b/main/src/cgeo/geocaching/cgeopoint.java @@ -7,6 +7,7 @@ import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.ui.Formatter; import cgeo.geocaching.utils.Log; +import cgeo.geocaching.utils.IObserver; import org.apache.commons.lang3.StringUtils; @@ -34,7 +35,7 @@ import android.widget.TextView; import java.util.List; -public class cgeopoint extends AbstractActivity { +public class cgeopoint extends AbstractActivity implements IObserver<IGeoData> { private static final int MENU_DEFAULT_NAVIGATION = 2; private static final int MENU_NAVIGATE = 0; private static final int MENU_CACHES_AROUND = 5; @@ -84,8 +85,6 @@ public class cgeopoint extends AbstractActivity { } } - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); private Button latButton = null; private Button lonButton = null; private boolean changed = false; @@ -146,7 +145,7 @@ public class cgeopoint extends AbstractActivity { historyListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { + ContextMenuInfo menuInfo) { menu.add(Menu.NONE, CONTEXT_MENU_NAVIGATE, Menu.NONE, res.getString(R.string.cache_menu_navigate)); menu.add(Menu.NONE, CONTEXT_MENU_EDIT_WAYPOINT, Menu.NONE, R.string.waypoint_edit); menu.add(Menu.NONE, CONTEXT_MENU_DELETE_WAYPOINT, Menu.NONE, R.string.waypoint_delete); @@ -164,7 +163,7 @@ public class cgeopoint extends AbstractActivity { case CONTEXT_MENU_NAVIGATE: contextMenuItemPosition = position; if (destination instanceof Destination) { - NavigationAppFactory.showNavigationMenu(geo, this, null, null, ((Destination) destination).getCoords()); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, null, null, ((Destination) destination).getCoords()); return true; } break; @@ -224,42 +223,27 @@ public class cgeopoint extends AbstractActivity { @Override public void onResume() { super.onResume(); - + app.addGeoObserver(this); init(); } @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(this); super.onPause(); } private void init() { - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - latButton = (Button) findViewById(R.id.buttonLatitude); lonButton = (Button) findViewById(R.id.buttonLongitude); @@ -305,7 +289,7 @@ public class cgeopoint extends AbstractActivity { if (latButton.getText().length() > 0 && lonButton.getText().length() > 0) { gp = new Geopoint(latButton.getText().toString() + " " + lonButton.getText().toString()); } - cgeocoords coordsDialog = new cgeocoords(cgeopoint.this, null, gp, geo); + cgeocoords coordsDialog = new cgeocoords(cgeopoint.this, null, gp, app.currentGeo()); coordsDialog.setCancelable(true); coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() { @Override @@ -400,7 +384,7 @@ public class cgeopoint extends AbstractActivity { return true; case MENU_NAVIGATE: - NavigationAppFactory.showNavigationMenu(geo, this, null, null, coords); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, null, null, coords); return true; default: return false; @@ -468,7 +452,7 @@ public class cgeopoint extends AbstractActivity { return; } - NavigationAppFactory.startDefaultNavigationApplication(geo, this, null, null, geopoint); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, null, null, geopoint); } private void cachesAround() { @@ -484,33 +468,27 @@ public class cgeopoint extends AbstractActivity { finish(); } - private class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - - try { - latButton.setHint(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); - lonButton.setHint(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); - } catch (Exception e) { - Log.w("Failed to update location."); - } + @Override + public void update(final IGeoData geo) { + try { + latButton.setHint(geo.getCoordsNow().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); + lonButton.setHint(geo.getCoordsNow().format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); + } catch (final Exception e) { + Log.w("Failed to update location."); } } private class currentListener implements View.OnClickListener { public void onClick(View arg0) { - if (geo == null || geo.coordsNow == null) { + final Geopoint coords = app.currentGeo().getCoordsNow(); + if (coords == null) { showToast(res.getString(R.string.err_point_unknown_position)); return; } - latButton.setText(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE)); - lonButton.setText(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE)); + latButton.setText(coords.format(GeopointFormatter.Format.LAT_DECMINUTE)); + lonButton.setText(coords.format(GeopointFormatter.Format.LON_DECMINUTE)); changed = false; } @@ -540,12 +518,12 @@ public class cgeopoint extends AbstractActivity { return null; } } else { - if (geo == null || geo.coordsNow == null) { + if (app.currentGeo().getCoordsNow() == null) { showToast(res.getString(R.string.err_point_curr_position_unavailable)); return null; } - coords = geo.coordsNow; + coords = app.currentGeo().getCoordsNow(); } if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) { diff --git a/main/src/cgeo/geocaching/cgeopopup.java b/main/src/cgeo/geocaching/cgeopopup.java index d60a81e..12af445 100644 --- a/main/src/cgeo/geocaching/cgeopopup.java +++ b/main/src/cgeo/geocaching/cgeopopup.java @@ -45,8 +45,7 @@ public class cgeopopup extends AbstractActivity { private LayoutInflater inflater = null; private String geocode = null; private cgCache cache = null; - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); + private GeoObserver geoUpdate = new UpdateLocation(); private ProgressDialog storeDialog = null; private ProgressDialog dropDialog = null; private TextView cacheDistance = null; @@ -202,7 +201,7 @@ public class cgeopopup extends AbstractActivity { navigateTo(); return true; } else if (menuItem == 3) { - NavigationAppFactory.showNavigationMenu(geo, this, cache, null, null); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, cache, null, null); return true; } else if (menuItem == 5) { cachesAround(); @@ -222,10 +221,6 @@ public class cgeopopup extends AbstractActivity { } private void init() { - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - app.setAction(geocode); cache = app.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); @@ -469,10 +464,6 @@ public class cgeopopup extends AbstractActivity { } catch (Exception e) { Log.e("cgeopopup.init: " + e.toString()); } - - if (geo != null) { - geoUpdate.updateLocation(geo); - } } @Override @@ -485,52 +476,37 @@ public class cgeopopup extends AbstractActivity { @Override public void onResume() { super.onResume(); - + app.addGeoObserver(geoUpdate); init(); } @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(geoUpdate); super.onPause(); } - private class update implements UpdateLocationCallback { + private class UpdateLocation extends GeoObserver { @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - + protected void updateLocation(final IGeoData geo) { try { - if (geo.coordsNow != null && cache != null && cache.getCoords() != null) { - cacheDistance.setText(HumanDistance.getHumanDistance(geo.coordsNow.distanceTo(cache.getCoords()))); + if (geo.getCoordsNow() != null && cache != null && cache.getCoords() != null) { + cacheDistance.setText(HumanDistance.getHumanDistance(geo.getCoordsNow().distanceTo(cache.getCoords()))); cacheDistance.bringToFront(); } } catch (Exception e) { - Log.w("Failed to update location."); + Log.w("Failed to UpdateLocation location."); } } } @@ -541,7 +517,7 @@ public class cgeopopup extends AbstractActivity { return; } - NavigationAppFactory.startDefaultNavigationApplication(geo, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, cache, null, null); } private void cachesAround() { @@ -651,7 +627,7 @@ public class cgeopopup extends AbstractActivity { showToast(res.getString(R.string.cache_coordinates_no)); return; } - NavigationAppFactory.startDefaultNavigationApplication(geo, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, cache, null, null); finish(); } @@ -663,7 +639,7 @@ public class cgeopopup extends AbstractActivity { showToast(res.getString(R.string.cache_coordinates_no)); return; } - NavigationAppFactory.startDefaultNavigationApplication2(geo, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication2(app.currentGeo(), this, cache, null, null); finish(); } diff --git a/main/src/cgeo/geocaching/cgeowaypoint.java b/main/src/cgeo/geocaching/cgeowaypoint.java index a6a4363..697ffd0 100644 --- a/main/src/cgeo/geocaching/cgeowaypoint.java +++ b/main/src/cgeo/geocaching/cgeowaypoint.java @@ -4,6 +4,7 @@ import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.apps.cache.navi.NavigationAppFactory; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; @@ -27,7 +28,7 @@ import android.widget.TextView; import java.util.EnumSet; -public class cgeowaypoint extends AbstractActivity { +public class cgeowaypoint extends AbstractActivity implements IObserver<IGeoData> { private static final int MENU_ID_NAVIGATION = 0; private static final int MENU_ID_CACHES_AROUND = 5; @@ -36,8 +37,6 @@ public class cgeowaypoint extends AbstractActivity { private cgWaypoint waypoint = null; private int id = -1; private ProgressDialog waitDialog = null; - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); private Handler loadWaypointHandler = new Handler() { @Override @@ -142,10 +141,6 @@ public class cgeowaypoint extends AbstractActivity { return; } - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true); waitDialog.setCancelable(true); @@ -165,10 +160,7 @@ public class cgeowaypoint extends AbstractActivity { public void onResume() { super.onResume(); - - if (geo == null) { - geo = app.startGeo(geoUpdate); - } + app.addGeoObserver(this); if (waitDialog == null) { waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true); @@ -180,28 +172,17 @@ public class cgeowaypoint extends AbstractActivity { @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(this); super.onPause(); } @@ -247,7 +228,7 @@ public class cgeowaypoint extends AbstractActivity { goToGeocache(); return true; } else if (menuItem == MENU_ID_NAVIGATION) { - NavigationAppFactory.showNavigationMenu(geo, this, null, waypoint, null); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, null, waypoint, null); return true; } return false; @@ -287,12 +268,9 @@ public class cgeowaypoint extends AbstractActivity { } } - private static class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - // nothing - } + @Override + public void update(final IGeoData geo) { + // nothing } private class editWaypointListener implements View.OnClickListener { @@ -330,7 +308,7 @@ public class cgeowaypoint extends AbstractActivity { return; } - NavigationAppFactory.startDefaultNavigationApplication(geo, this, null, waypoint, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, null, waypoint, null); } /** @@ -341,7 +319,7 @@ public class cgeowaypoint extends AbstractActivity { return; } - NavigationAppFactory.startDefaultNavigationApplication2(geo, this, null, waypoint, null); + NavigationAppFactory.startDefaultNavigationApplication2(app.currentGeo(), this, null, waypoint, null); } private boolean navigationPossible() { @@ -367,7 +345,7 @@ public class cgeowaypoint extends AbstractActivity { if (handled) { return true; } - return NavigationAppFactory.onMenuItemSelected(item, geo, this, null, waypoint, null); + return NavigationAppFactory.onMenuItemSelected(item, app.currentGeo(), this, null, waypoint, null); } public static void startActivity(final Context context, final int waypointId) { diff --git a/main/src/cgeo/geocaching/cgeowaypointadd.java b/main/src/cgeo/geocaching/cgeowaypointadd.java index 3d4c4c1..7db53d2 100644 --- a/main/src/cgeo/geocaching/cgeowaypointadd.java +++ b/main/src/cgeo/geocaching/cgeowaypointadd.java @@ -9,6 +9,7 @@ import cgeo.geocaching.geopoint.DistanceParser; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.utils.BaseUtils; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; @@ -31,12 +32,10 @@ import java.util.ArrayList; import java.util.EnumSet; import java.util.List; -public class cgeowaypointadd extends AbstractActivity { +public class cgeowaypointadd extends AbstractActivity implements IObserver<IGeoData> { private String geocode = null; private int id = -1; - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); private ProgressDialog waitDialog = null; private cgWaypoint waypoint = null; private Geopoint gpTemp = null; @@ -104,10 +103,6 @@ public class cgeowaypointadd extends AbstractActivity { setContentView(R.layout.waypoint_new); setTitle("waypoint"); - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - // get parameters Bundle extras = getIntent().getExtras(); if (extras != null) { @@ -170,10 +165,7 @@ public class cgeowaypointadd extends AbstractActivity { public void onResume() { super.onResume(); - - if (geo == null) { - geo = app.startGeo(geoUpdate); - } + app.addGeoObserver(this); if (id > 0) { if (waitDialog == null) { @@ -187,28 +179,17 @@ public class cgeowaypointadd extends AbstractActivity { @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(this); super.onPause(); } @@ -249,23 +230,20 @@ public class cgeowaypointadd extends AbstractActivity { distanceUnitSelector.setOnItemSelectedListener(new changeDistanceUnit(this)); } - private class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - Log.d("cgeowaypointadd.updateLocation called"); - if (geo == null || geo.coordsNow == null) { - return; - } + @Override + public void update(final IGeoData geo) { + Log.d("cgeowaypointadd.updateLocation called"); + if (geo.getCoordsNow() == null) { + return; + } - try { - Button bLat = (Button) findViewById(R.id.buttonLatitude); - Button bLon = (Button) findViewById(R.id.buttonLongitude); - bLat.setHint(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); - bLon.setHint(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); - } catch (Exception e) { - Log.w("Failed to update location."); - } + try { + Button bLat = (Button) findViewById(R.id.buttonLatitude); + Button bLon = (Button) findViewById(R.id.buttonLongitude); + bLat.setHint(geo.getCoordsNow().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); + bLon.setHint(geo.getCoordsNow().format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); + } catch (Exception e) { + Log.w("Failed to update location."); } } @@ -293,7 +271,7 @@ public class cgeowaypointadd extends AbstractActivity { gp = gpTemp; } cgCache cache = app.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS); - cgeocoords coordsDialog = new cgeocoords(cgeowaypointadd.this, cache, gp, geo); + cgeocoords coordsDialog = new cgeocoords(cgeowaypointadd.this, cache, gp, app.currentGeo()); coordsDialog.setCancelable(true); coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() { @Override @@ -378,11 +356,14 @@ public class cgeowaypointadd extends AbstractActivity { showToast(res.getString(e.resource)); return; } - } else if (geo == null || geo.coordsNow == null) { - showToast(res.getString(R.string.err_point_curr_position_unavailable)); - return; } else { - coords = geo.coordsNow; + final IGeoData geo = app.currentGeo(); + if (geo.getCoordsNow() == null) { + showToast(res.getString(R.string.err_point_curr_position_unavailable)); + return; + } else { + coords = geo.getCoordsNow(); + } } if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) { diff --git a/main/src/cgeo/geocaching/connector/gc/GCBase.java b/main/src/cgeo/geocaching/connector/gc/GCBase.java index 4ba1be6..e7b22ff 100644 --- a/main/src/cgeo/geocaching/connector/gc/GCBase.java +++ b/main/src/cgeo/geocaching/connector/gc/GCBase.java @@ -4,6 +4,7 @@ import cgeo.geocaching.ICoordinates; import cgeo.geocaching.SearchResult; import cgeo.geocaching.Settings; import cgeo.geocaching.cgCache; +import cgeo.geocaching.cgeo; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; @@ -68,7 +69,7 @@ public class GCBase { public static SearchResult searchByViewport(final Viewport viewport, final String[] tokens) { Strategy strategy = Settings.getLiveMapStrategy(); if (strategy == Strategy.AUTO) { - float speedNow = cgeoapplication.getInstance().getSpeedFromGeo(); + float speedNow = cgeoapplication.getInstance().currentGeo().getSpeedNow(); strategy = speedNow >= 8 ? Strategy.FAST : Strategy.DETAILED; // 8 m/s = 30 km/h } // return searchByViewport(viewport, tokens, strategy); @@ -77,7 +78,7 @@ public class GCBase { { SearchResult result = searchByViewport(viewport, tokens, strategy); String text = Formatter.SEPARATOR + strategy.getL10n() + Formatter.SEPARATOR; - int speed = (int) cgeoapplication.getInstance().getSpeedFromGeo(); + int speed = (int) cgeoapplication.getInstance().currentGeo().getSpeedNow(); if (Settings.isUseMetricUnits()) { text += speed + " km/h"; } else { diff --git a/main/src/cgeo/geocaching/maps/CGeoMap.java b/main/src/cgeo/geocaching/maps/CGeoMap.java index d3c08e8..7a3d1a0 100644 --- a/main/src/cgeo/geocaching/maps/CGeoMap.java +++ b/main/src/cgeo/geocaching/maps/CGeoMap.java @@ -1,5 +1,7 @@ package cgeo.geocaching.maps; +import cgeo.geocaching.GeoObserver; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.IWaypoint; import cgeo.geocaching.LiveMapInfo; import cgeo.geocaching.R; @@ -7,14 +9,12 @@ import cgeo.geocaching.SearchResult; import cgeo.geocaching.Settings; import cgeo.geocaching.StoredList; import cgeo.geocaching.UpdateDirectionCallback; -import cgeo.geocaching.UpdateLocationCallback; +import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgDirection; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.cgeocaches; -import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.gc.GCBase; import cgeo.geocaching.connector.gc.Login; @@ -121,9 +121,8 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto private MapViewImpl mapView = null; private MapControllerImpl mapController = null; private cgeoapplication app = null; - private cgGeo geo = null; private cgDirection dir = null; - private UpdateLocationCallback geoUpdate = new UpdateLoc(); + final private GeoObserver geoUpdate = new UpdateLoc(); private UpdateDirectionCallback dirUpdate = new UpdateDir(); private SearchResult searchIntent = null; private String geocodeIntent = null; @@ -283,9 +282,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto waitDialog.setOnCancelListener(null); } - if (geo == null) { - geo = app.startGeo(geoUpdate); - } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } @@ -298,9 +294,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto loadDetailsThread.stopIt(); } - if (geo == null) { - geo = app.startGeo(geoUpdate); - } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } @@ -402,9 +395,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto activity.setContentView(mapProvider.getMapLayoutId()); ActivityMixin.setTitle(activity, res.getString(R.string.map_map)); - if (geo == null) { - geo = app.startGeo(geoUpdate); - } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } @@ -442,9 +432,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto mapController.setZoom(Settings.getMapZoom()); // start location and directory services - if (geo != null) { - geoUpdate.updateLocation(geo); - } if (dir != null) { dirUpdate.updateDirection(dir); } @@ -498,15 +485,11 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto } app.setAction(StringUtils.defaultIfBlank(geocodeIntent, null)); - if (geo == null) { - geo = app.startGeo(geoUpdate); - } + app.addGeoObserver(geoUpdate); if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } - geoUpdate.updateLocation(geo); - if (dir != null) { dirUpdate.updateDirection(dir); } @@ -541,9 +524,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto if (dir != null) { dir = app.removeDir(); } - if (geo != null) { - geo = app.removeGeo(); - } savePrefs(); @@ -569,9 +549,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto if (dir != null) { dir = app.removeDir(); } - if (geo != null) { - geo = app.removeGeo(); - } + app.deleteGeoObserver(geoUpdate); savePrefs(); @@ -597,9 +575,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto if (dir != null) { dir = app.removeDir(); } - if (geo != null) { - geo = app.removeGeo(); - } savePrefs(); @@ -746,9 +721,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto loadDetailsThread.stopIt(); } - if (geo == null) { - geo = app.startGeo(geoUpdate); - } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } @@ -897,21 +869,17 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto } // Set center of map to my location if appropriate. - private void myLocationInMiddle() { - if (followMyLocation && geo != null) { - centerMap(geo.coordsNow); + private void myLocationInMiddle(final IGeoData geo) { + if (followMyLocation) { + centerMap(geo.getCoordsNow()); } } // class: update location - private class UpdateLoc implements UpdateLocationCallback { + private class UpdateLoc extends GeoObserver { @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - + protected void updateLocation(final IGeoData geo) { try { boolean repaintRequired = false; @@ -919,20 +887,20 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto overlayPosition = mapView.createAddPositionOverlay(activity); } - if (overlayPosition != null && geo.location != null) { - overlayPosition.setCoordinates(geo.location); + if (overlayPosition != null && geo.getLocation() != null) { + overlayPosition.setCoordinates(geo.getLocation()); } - if (geo.coordsNow != null) { + if (geo.getCoordsNow() != null) { if (followMyLocation) { - myLocationInMiddle(); + myLocationInMiddle(geo); } else { repaintRequired = true; } } - if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h - overlayPosition.setHeading(geo.bearingNow); + if (!Settings.isUseCompass() || geo.getSpeedNow() > 5) { // use GPS when speed is higher than 18 km/h + overlayPosition.setHeading(geo.getBearingNow()); repaintRequired = true; } @@ -955,7 +923,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto return; } - if (overlayPosition != null && mapView != null && (geo == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h + if (overlayPosition != null && mapView != null && (app.currentGeo().getSpeedNow() <= 5)) { // use compass when speed is lower than 18 km/h overlayPosition.setHeading(dir.directionNow); mapView.repaintRequired(overlayPosition); } @@ -1462,11 +1430,10 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto if (dir != null) { dir = app.removeDir(); } - if (geo != null) { - geo = app.removeGeo(); - } - for (String geocode : geocodes) { + app.deleteGeoObserver(geoUpdate); + + for (final String geocode : geocodes) { try { if (handler.isCancelled()) { break; @@ -1510,6 +1477,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto // we're done handler.sendEmptyMessage(FINISHED_LOADING_DETAILS); + app.addGeoObserver(geoUpdate); } } @@ -1591,7 +1559,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto private void switchMyLocationButton() { if (followMyLocation) { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_on); - myLocationInMiddle(); + myLocationInMiddle(app.currentGeo()); } else { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_off); } |