aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/sensors/GeoDataProvider.java
blob: 7645d7f86b21003bf9b103e14a84be5e41a1e80b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package cgeo.geocaching.sensors;

import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.RxUtils.ConnectableLooperCallbacks;

import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.observables.ConnectableObservable;
import rx.subjects.BehaviorSubject;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import java.util.concurrent.TimeUnit;

public class GeoDataProvider implements OnSubscribe<IGeoData> {

    private final LocationManager geoManager;
    private final LocationData gpsLocation = new LocationData();
    private final LocationData netLocation = new LocationData();
    private final BehaviorSubject<IGeoData> subject;

    private static class LocationData {
        public Location location;
        public long timestamp = 0;

        public void update(final Location location) {
            this.location = location;
            timestamp = System.currentTimeMillis();
        }

        public boolean isRecent() {
            return isValid() && System.currentTimeMillis() < timestamp + 30000;
        }

        public boolean isValid() {
            return location != null;
        }
    }

    /**
     * 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 context the context used to retrieve the system services
     */
    protected GeoDataProvider(final Context context) {
        geoManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        subject = BehaviorSubject.create(findInitialLocation());
    }

    public static Observable<IGeoData> create(final Context context) {
        final GeoDataProvider provider = new GeoDataProvider(context);
        return provider.worker.refCount();
    }

    @Override
    public void call(final Subscriber<? super IGeoData> subscriber) {
        subject.subscribe(subscriber);
    }

    final ConnectableObservable<IGeoData> worker = new ConnectableLooperCallbacks<IGeoData>(this, 2500, TimeUnit.MILLISECONDS) {
        private final Listener networkListener = new Listener(LocationManager.NETWORK_PROVIDER, netLocation);
        private final Listener gpsListener = new Listener(LocationManager.GPS_PROVIDER, gpsLocation);

        @Override
        protected void onStart() {
            Log.d("GeoDataProvider: starting the GPS and network listeners");
            for (final Listener listener : new Listener[]{networkListener, gpsListener}) {
                try {
                    geoManager.requestLocationUpdates(listener.locationProvider, 0, 0, listener);
                } catch (final Exception e) {
                    Log.w("There is no location provider " + listener.locationProvider);
                }
            }
        }

        @Override
        protected void onStop() {
            Log.d("GeoDataProvider: stopping the GPS and network listeners");
            geoManager.removeUpdates(networkListener);
            geoManager.removeUpdates(gpsListener);
        }
    };

    private IGeoData findInitialLocation() {
        final Location initialLocation = new Location("initial");
        try {
            // Try to find a sensible initial location from the last locations known to Android.
            final Location lastGpsLocation = geoManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            final Location lastNetworkLocation = geoManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            // If both providers are non-null, take the most recent one
            if (lastGpsLocation != null && lastNetworkLocation != null) {
                if (lastGpsLocation.getTime() >= lastNetworkLocation.getTime()) {
                    copyCoords(initialLocation, lastGpsLocation);
                } else {
                    copyCoords(initialLocation, lastNetworkLocation);
                }
            } else if (lastGpsLocation != null) {
                copyCoords(initialLocation, lastGpsLocation);
            } else if (lastNetworkLocation != null) {
                copyCoords(initialLocation, lastNetworkLocation);
            } else {
                Log.i("GeoDataProvider: no last known location available");
            }
        } catch (final Exception e) {
            // This error is non-fatal as its only consequence is that we will start with a dummy location
            // instead of a previously known one.
            Log.e("GeoDataProvider: error when retrieving last known location", e);
        }
        // Start with an historical GeoData just in case someone queries it before we get
        // a chance to get any information.
        return new GeoData(initialLocation);
    }

    private static void copyCoords(final Location target, final Location source) {
        target.setLatitude(source.getLatitude());
        target.setLongitude(source.getLongitude());
    }

    private class Listener implements LocationListener {
        private final String locationProvider;
        private final LocationData locationData;

        Listener(final String locationProvider, final LocationData locationData) {
            this.locationProvider = locationProvider;
            this.locationData = locationData;
        }

        @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
        }

        @Override
        public void onLocationChanged(final Location location) {
            locationData.update(location);
            selectBest();
        }
    }

    private LocationData best() {
        if (gpsLocation.isRecent() || !netLocation.isValid()) {
            return gpsLocation.isValid() ? gpsLocation : null;
        }
        if (!gpsLocation.isValid()) {
            return netLocation;
        }
        return gpsLocation.timestamp > netLocation.timestamp ? gpsLocation : netLocation;
    }

    private void selectBest() {
        assign(best());
    }

    private void assign(final LocationData locationData) {
        if (locationData == null) {
            return;
        }

        // We do not necessarily get signalled when satellites go to 0/0.
        final IGeoData current = new GeoData(locationData.location);
        subject.onNext(current);
    }

}