-
-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathGPSLogger.java
More file actions
485 lines (419 loc) · 15.8 KB
/
GPSLogger.java
File metadata and controls
485 lines (419 loc) · 15.8 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package net.osmtracker.service.gps;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import net.osmtracker.OSMTracker;
import net.osmtracker.R;
import net.osmtracker.activity.TrackLogger;
import net.osmtracker.db.DataHelper;
import net.osmtracker.db.TrackContentProvider;
import net.osmtracker.listener.PressureListener;
import net.osmtracker.listener.SensorListener;
import net.osmtracker.osm.OpenStreetMapConstants;
/**
* GPS logging service.
*
* @author Nicolas Guillaumin
*
*/
public class GPSLogger extends Service implements LocationListener {
private static final String TAG = GPSLogger.class.getSimpleName();
/**
* Data helper.
*/
private DataHelper dataHelper;
/**
* Are we currently tracking ?
*/
private boolean isTracking = false;
/**
* Is GPS enabled ?
*/
private boolean isGpsEnabled = false;
/**
* Minimum accuracy in meters for starting
*/
private int minAccuracy = 0;
/**
* Precision of the accuracy in meters is satisfied ?
*/
private boolean isAccuracySatisfied = false;
/**
* Precision of the accuracy in meters is satisfied ?
*/
private boolean isAccuracySatisfied = false;
/**
* Use barometer yes/no ?
*/
private boolean use_barometer = false;
/**
* System notification id.
*/
private static final int NOTIFICATION_ID = 1;
private static String CHANNEL_ID = "GPSLogger_Channel";
/**
* Last known location
*/
private Location lastLocation;
/**
* LocationManager
*/
private LocationManager lmgr;
/**
* Current Track ID
*/
private long currentTrackId = -1;
/**
* Current Segment ID
*/
private long currentSegmentId = -1;
/**
* the timestamp of the last GPS fix we used
*/
private long lastGPSTimestamp = 0;
/**
* the interval (in ms) to log GPS fixes defined in the preferences
*/
private long gpsLoggingInterval;
private long gpsLoggingMinDistance;
/**
* Minimum accuracy in meters for starting defined in the preferences
*/
private long gpsLoggingMinAccuracy;
/**
* sensors for magnetic orientation
*/
private SensorListener sensorListener = new SensorListener();
/**
* sensor for atmospheric pressure
*/
private PressureListener pressureListener = new PressureListener();
/**
* Receives Intent for way point and notes tracking, and stop/start logging.
*/
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Received intent " + intent.getAction());
if (OSMTracker.INTENT_TRACK_WP.equals(intent.getAction())) {
// Track a way point
Bundle extras = intent.getExtras();
if (extras != null) {
// because of the gps logging interval our last fix could be very old
// so we'll request the last known location from the gps provider
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
lastLocation = lmgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null) {
Long trackId = extras.getLong(TrackContentProvider.Schema.COL_TRACK_ID);
String uuid = extras.getString(OSMTracker.INTENT_KEY_UUID);
String name = extras.getString(OSMTracker.INTENT_KEY_NAME);
String link = extras.getString(OSMTracker.INTENT_KEY_LINK);
dataHelper.wayPoint(trackId, lastLocation, name, link, uuid, sensorListener.getAzimuth(), sensorListener.getAccuracy(), pressureListener.getPressure());
// If there is a waypoint in the track, there should also be a trackpoint
dataHelper.track(currentTrackId, lastLocation, sensorListener.getAzimuth(), sensorListener.getAccuracy(), pressureListener.getPressure(), currentSegmentId);
}
}
}
} else if (OSMTracker.INTENT_UPDATE_WP.equals(intent.getAction())) {
// Update an existing waypoint
Bundle extras = intent.getExtras();
if (extras != null) {
Long trackId = extras.getLong(TrackContentProvider.Schema.COL_TRACK_ID);
String uuid = extras.getString(OSMTracker.INTENT_KEY_UUID);
String name = extras.getString(OSMTracker.INTENT_KEY_NAME);
String link = extras.getString(OSMTracker.INTENT_KEY_LINK);
dataHelper.updateWayPoint(trackId, uuid, name, link);
}
} else if (OSMTracker.INTENT_DELETE_WP.equals(intent.getAction())) {
// Delete an existing waypoint
Bundle extras = intent.getExtras();
if (extras != null) {
Long trackId = extras.getLong(TrackContentProvider.Schema.COL_TRACK_ID);
String uuid = extras.getString(OSMTracker.INTENT_KEY_UUID);
String link = extras.getString(OSMTracker.INTENT_KEY_LINK);
String filePath = null;
try {
filePath = link.equals("null") ? null : DataHelper.getTrackDirectory(trackId, context) + "/" + link;
}
catch(NullPointerException ne){}
dataHelper.deleteWayPoint(uuid, filePath);
}
} else if (OSMTracker.INTENT_TRACK_NOTE.equals(intent.getAction())) {
// Track a note
Bundle extras = intent.getExtras();
if (extras != null) {
// because of the gps logging interval our last fix could be very old
// so we'll request the last known location from the gps provider
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
lastLocation = lmgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null) {
//TODO: CHECK THIS
long trackId = extras.getLong(TrackContentProvider.Schema.COL_TRACK_ID);
String uuid = extras.getString(OSMTracker.INTENT_KEY_UUID);
String name = extras.getString(OSMTracker.INTENT_KEY_NAME);
dataHelper.trackNote(trackId, lastLocation, name, uuid);
}
}
}
} else if (OSMTracker.INTENT_UPDATE_NOTE.equals(intent.getAction())) {
// Update an existing note
Bundle extras = intent.getExtras();
if (extras != null) {
long trackId = extras.getLong(TrackContentProvider.Schema.COL_TRACK_ID);
String uuid = extras.getString(OSMTracker.INTENT_KEY_UUID);
String name = extras.getString(OSMTracker.INTENT_KEY_NAME);
dataHelper.updateNote(trackId, uuid, name);
}
} else if (OSMTracker.INTENT_START_TRACKING.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
if (extras != null) {
Long trackId = extras.getLong(TrackContentProvider.Schema.COL_TRACK_ID);
startTracking(trackId);
}
} else if (OSMTracker.INTENT_STOP_TRACKING.equals(intent.getAction())) {
stopTrackingAndSave();
}
}
};
/**
* Binder for service interaction
*/
private final IBinder binder = new GPSLoggerBinder();
@Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "Service onBind()");
return binder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.v(TAG, "Service onUnbind()");
// If we aren't currently tracking we can
// stop ourselves
if (! isTracking ) {
Log.v(TAG, "Service self-stopping");
stopSelf();
}
// We don't want onRebind() to be called, so return false.
return false;
}
/**
* Bind interface for service interaction
*/
public class GPSLoggerBinder extends Binder {
/**
* Called by the activity when binding.
* Returns itself.
* @return the GPS Logger service
*/
public GPSLogger getService() {
return GPSLogger.this;
}
}
@Override
public void onCreate() {
Log.v(TAG, "Service onCreate()");
dataHelper = new DataHelper(this);
//read the logging interval from preferences
gpsLoggingInterval = Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getString(
OSMTracker.Preferences.KEY_GPS_LOGGING_INTERVAL, OSMTracker.Preferences.VAL_GPS_LOGGING_INTERVAL)) * 1000;
gpsLoggingMinDistance = Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getString(
OSMTracker.Preferences.KEY_GPS_LOGGING_MIN_DISTANCE, OSMTracker.Preferences.VAL_GPS_LOGGING_MIN_DISTANCE));
gpsLoggingMinAccuracy = Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getString(
OSMTracker.Preferences.KEY_GPS_LOGGING_MIN_ACCURACY, OSMTracker.Preferences.VAL_GPS_LOGGING_MIN_ACCURACY));
use_barometer = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()).getBoolean(
OSMTracker.Preferences.KEY_USE_BAROMETER, OSMTracker.Preferences.VAL_USE_BAROMETER);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
try {
minAccuracy = Integer.parseInt(prefs.getString(
OSMTracker.Preferences.KEY_GPS_MIN_ACCURACY,
OSMTracker.Preferences.VAL_GPS_MIN_ACCURACY));
} catch (NumberFormatException e) {
minAccuracy = Integer.parseInt(OSMTracker.Preferences.VAL_GPS_MIN_ACCURACY);
}
// minimum precision enabled
if (minAccuracy == 0) {
isAccuracySatisfied = true;
}
// Register our broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction(OSMTracker.INTENT_TRACK_WP);
filter.addAction(OSMTracker.INTENT_UPDATE_WP);
filter.addAction(OSMTracker.INTENT_TRACK_NOTE);
filter.addAction(OSMTracker.INTENT_UPDATE_NOTE);
filter.addAction(OSMTracker.INTENT_DELETE_WP);
filter.addAction(OSMTracker.INTENT_START_TRACKING);
filter.addAction(OSMTracker.INTENT_STOP_TRACKING);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED);
} else {
registerReceiver(receiver, filter);
}
// Register ourselves for location updates
lmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
lmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, gpsLoggingInterval, gpsLoggingMinDistance, this);
}
//register for Orientation updates
sensorListener.register(this);
// register for atmospheric pressure updates
pressureListener.register(this, use_barometer);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "Service onStartCommand(-,"+flags+","+startId+")");
createNotificationChannel();
startForeground(NOTIFICATION_ID, getNotification());
return Service.START_STICKY;
}
@Override
public void onDestroy() {
Log.v(TAG, "Service onDestroy()");
if (isTracking) {
// If we're currently tracking, save user data.
stopTrackingAndSave();
}
// Unregister listener
lmgr.removeUpdates(this);
// Unregister broadcast receiver
unregisterReceiver(receiver);
// Cancel any existing notification
stopNotifyBackgroundService();
// stop sensors
sensorListener.unregister();
pressureListener.unregister();
super.onDestroy();
}
/**
* Start GPS tracking.
*/
private void startTracking(long trackId) {
currentTrackId = trackId;
currentSegmentId = DataHelper.getSegmentIdFor(trackId, getContentResolver()) + 1;
Log.v(TAG, "Starting track logging for track #" + trackId + " segment #" +"/" + currentSegmentId);
// Refresh notification with correct Track ID
NotificationManager nmgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nmgr.notify(NOTIFICATION_ID, getNotification());
isTracking = true;
}
/**
* Stops GPS Logging
*/
private void stopTrackingAndSave() {
isTracking = false;
dataHelper.stopTracking(currentTrackId);
currentTrackId = -1;
this.stopSelf();
}
@Override
public void onLocationChanged(Location location) {
if (location == null){
return;
}
// Wait for minimum accuracy before starting
if(!isAccuracySatisfied){
if(location.hasAccuracy() && location.getAccuracy() <= gpsLoggingMinAccuracy){
// Precision achieved we unlocked the door and began recording this one and the following ones.
isAccuracySatisfied = true;
}
else {
return;
}
}
// We're receiving location, so GPS is enabled
isGpsEnabled = true;
// first of all we check if the time from the last used fix to the current fix is greater than the logging interval
if((lastGPSTimestamp + gpsLoggingInterval) < System.currentTimeMillis()){
lastGPSTimestamp = System.currentTimeMillis(); // save the time of this fix
lastLocation = location;
if (isTracking) {
dataHelper.track(currentTrackId, location, sensorListener.getAzimuth(), sensorListener.getAccuracy(), pressureListener.getPressure(), currentSegmentId);
}
}
}
/**
* Builds the notification to display when tracking in background.
*/
private Notification getNotification() {
Intent startTrackLogger = new Intent(this, TrackLogger.class);
startTrackLogger.putExtra(TrackContentProvider.Schema.COL_TRACK_ID, currentTrackId);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, startTrackLogger, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_track)
.setContentTitle(getResources().getString(R.string.notification_title).replace("{0}", (currentTrackId > -1) ? Long.toString(currentTrackId) : "?"))
.setContentText(getResources().getString(R.string.notification_text))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(contentIntent)
.setAutoCancel(true);
return mBuilder.build();
}
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// FIXME: following two strings must be obtained from 'R.string' to support translations
CharSequence name = "GPS Logger";
String description = "Display when tracking in Background";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
/**
* Stops notifying the user that we're tracking in the background
*/
private void stopNotifyBackgroundService() {
NotificationManager nmgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nmgr.cancel(NOTIFICATION_ID);
}
@Override
public void onProviderDisabled(String provider) {
isGpsEnabled = false;
}
@Override
public void onProviderEnabled(String provider) {
isGpsEnabled = true;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// Not interested in provider status
}
/**
* Getter for gpsEnabled
* @return true if GPS is enabled, otherwise false.
*/
public boolean isGpsEnabled() {
return isGpsEnabled;
}
/**
* Setter for isTracking
* @return true if we're currently tracking, otherwise false.
*/
public boolean isTracking() {
return isTracking;
}
}