forked from criticalmaps/criticalmaps-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocationUpdateManager.java
More file actions
281 lines (238 loc) · 10.5 KB
/
LocationUpdateManager.java
File metadata and controls
281 lines (238 loc) · 10.5 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package de.stephanlindauer.criticalmaps.managers;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import com.squareup.otto.Produce;
import org.osmdroid.util.GeoPoint;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import de.stephanlindauer.criticalmaps.App;
import de.stephanlindauer.criticalmaps.R;
import de.stephanlindauer.criticalmaps.events.Events;
import de.stephanlindauer.criticalmaps.events.GpsStatusChangedEvent;
import de.stephanlindauer.criticalmaps.events.NewLocationEvent;
import de.stephanlindauer.criticalmaps.handler.PermissionCheckHandler;
import de.stephanlindauer.criticalmaps.model.OwnLocationModel;
import de.stephanlindauer.criticalmaps.model.PermissionRequest;
import de.stephanlindauer.criticalmaps.provider.EventBus;
@Singleton
public class LocationUpdateManager {
private final OwnLocationModel ownLocationModel;
private final EventBus eventBus;
private final PermissionCheckHandler permissionCheckHandler;
private final App app;
private boolean isUpdating = false;
private boolean isEventBusRegistered = false;
private static final float LOCATION_REFRESH_DISTANCE = 20; //20 meters
private static final long LOCATION_REFRESH_TIME = 12 * 1000; //12 seconds
private static final int LOCATION_NEW_THRESHOLD = 30 * 1000; //30 seconds
private final String[] USED_PROVIDERS = new String[]{
LocationManager.GPS_PROVIDER,
LocationManager.NETWORK_PROVIDER};
@SuppressLint("InlinedApi")
private final String[] PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.POST_NOTIFICATIONS};
private final LocationManager locationManager;
private Location lastPublishedLocation;
private final LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
if (shouldPublishNewLocation(location)) {
publishNewLocation(location);
lastPublishedLocation = location;
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// Notes after some testing:
// - seems to be only called for GPS provider
// - calls not necessarily consistent with location fixes
// - recurrent AVAILABLE calls for GPS
// -> not usable
}
@Override
public void onProviderEnabled(String s) {
postStatusEvent();
}
@Override
public void onProviderDisabled(String s) {
postStatusEvent();
}
};
@Inject
public LocationUpdateManager(App app,
OwnLocationModel ownLocationModel,
EventBus eventBus,
PermissionCheckHandler permissionCheckHandler) {
this.app = app;
this.ownLocationModel = ownLocationModel;
this.eventBus = eventBus;
this.permissionCheckHandler = permissionCheckHandler;
locationManager = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE);
}
@Produce
public GpsStatusChangedEvent produceStatusEvent() {
return Events.GPS_STATUS_CHANGED_EVENT;
}
@Produce
public NewLocationEvent produceLocationEvent() {
return Events.NEW_LOCATION_EVENT;
}
private void postStatusEvent() {
setStatusEvent();
eventBus.post(Events.GPS_STATUS_CHANGED_EVENT);
}
private void setAndPostPermissionPermanentlyDeniedEvent() {
Events.GPS_STATUS_CHANGED_EVENT.status =
GpsStatusChangedEvent.Status.PERMISSION_PERMANENTLY_DENIED;
eventBus.post(Events.GPS_STATUS_CHANGED_EVENT);
}
private void setStatusEvent() {
// isProviderEnabled() doesn't throw when permission is not granted, so we can use it safely
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.HIGH_ACCURACY;
isUpdating = true;
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.LOW_ACCURACY;
isUpdating = true;
} else {
isUpdating = false;
Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.DISABLED;
}
}
private boolean checkIfAtLeastOneProviderExits() {
final List<String> allProviders = locationManager.getAllProviders();
boolean atLeastOneProviderExists = false;
for (String provider : USED_PROVIDERS) {
if (allProviders.contains(provider)) {
atLeastOneProviderExists = true;
break;
}
}
return atLeastOneProviderExists;
}
// Usage of this method should rather be handled by listening to the GpsStatusChangedEvent,
// unfortunately this is not possible in PullServerHandler because we can't register on non
// main thread
public boolean isUpdating() {
return isUpdating;
}
public void initialize() {
boolean noProviderExists = !checkIfAtLeastOneProviderExits();
boolean noPermission = !checkPermission();
if (noProviderExists) {
Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.NONEXISTENT;
} else if (noPermission) {
Events.GPS_STATUS_CHANGED_EVENT.status = GpsStatusChangedEvent.Status.NO_PERMISSIONS;
} else {
setStatusEvent();
}
if(!isEventBusRegistered) {
eventBus.register(this);
isEventBusRegistered = true;
}
// Short-circuit here: if no provider exists don't start listening
if (noProviderExists) {
return;
}
// If permissions are not granted, don't start listening
if (noPermission) {
return;
}
}
public void startListening() {
// Set GPS status in case we're coming back after permission request
postStatusEvent();
// To get a quick first location, query all providers for last known location and treat them
// like regular fixes by piping them through our normal flow
final List<String> providers = locationManager.getAllProviders();
for (String provider : providers) {
@SuppressLint("MissingPermission")
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
locationListener.onLocationChanged(location);
}
}
registerLocationListeners();
}
private void registerLocationListeners() {
// register existing providers; if one isn't enabled, the listener will take care of that
requestLocationUpdatesIfProviderExists(LocationManager.GPS_PROVIDER);
requestLocationUpdatesIfProviderExists(LocationManager.NETWORK_PROVIDER);
}
@SuppressLint("MissingPermission")
private void requestLocationUpdatesIfProviderExists(String provider) {
if (locationManager.getProvider(provider) != null) {
locationManager.requestLocationUpdates(provider,
LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE,
locationListener);
}
}
@SuppressLint("InlinedApi")
public static boolean checkPermission() {
App app = App.components().app();
return (ContextCompat.checkSelfPermission(app, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(app, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
&& ContextCompat.checkSelfPermission(app, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED;
}
public void requestPermission() {
PermissionRequest permissionRequest = new PermissionRequest(
PERMISSIONS,
app.getString(R.string.map_location_permissions_rationale_text),
this::startListening,
null,
this::setAndPostPermissionPermanentlyDeniedEvent);
permissionCheckHandler.requestPermissionsWithRationaleIfNeeded(permissionRequest);
}
public void handleShutdown() {
locationManager.removeUpdates(locationListener);
try {
eventBus.unregister(this);
} catch (IllegalArgumentException ignored) {
// nothing we can do
}
isEventBusRegistered = false;
}
private void publishNewLocation(Location location) {
GeoPoint newLocation = new GeoPoint(location.getLatitude(), location.getLongitude());
ownLocationModel.setLocation(newLocation, location.getAccuracy());
eventBus.post(Events.NEW_LOCATION_EVENT);
}
private boolean shouldPublishNewLocation(Location location) {
// Any location is better than no location
if (lastPublishedLocation == null) {
return true;
}
// Average speed of the CM is ~4 m/s so anything over 30 seconds old, may already
// be well over 120m off. So a newer fix is assumed to be always better.
long timeDelta = location.getTime() - lastPublishedLocation.getTime();
boolean isSignificantlyNewer = timeDelta > LOCATION_NEW_THRESHOLD;
boolean isSignificantlyOlder = timeDelta < -LOCATION_NEW_THRESHOLD;
boolean isNewer = timeDelta > 0;
if (isSignificantlyNewer) {
return true;
} else if (isSignificantlyOlder) {
return false;
}
int accuracyDelta = (int) (location.getAccuracy() - lastPublishedLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 120;
boolean isFromSameProvider = location.getProvider().equals(lastPublishedLocation.getProvider());
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else return isNewer && !isSignificantlyLessAccurate && isFromSameProvider;
}
}