-
Notifications
You must be signed in to change notification settings - Fork 564
/
BackgroundGeolocationModule.java
405 lines (349 loc) · 14.1 KB
/
BackgroundGeolocationModule.java
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
package com.marianhello.bgloc.react;
import android.content.Context;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.marianhello.bgloc.BackgroundGeolocationFacade;
import com.marianhello.bgloc.Config;
import com.marianhello.bgloc.LocationService;
import com.marianhello.bgloc.PluginDelegate;
import com.marianhello.bgloc.PluginException;
import com.marianhello.bgloc.data.BackgroundActivity;
import com.marianhello.bgloc.data.BackgroundLocation;
import com.marianhello.bgloc.react.data.LocationMapper;
import com.marianhello.logging.LogEntry;
import com.marianhello.logging.LoggerManager;
import org.json.JSONException;
import java.util.Collection;
public class BackgroundGeolocationModule extends ReactContextBaseJavaModule implements LifecycleEventListener, PluginDelegate {
public static final String LOCATION_EVENT = "location";
public static final String STATIONARY_EVENT = "stationary";
public static final String ACTIVITY_EVENT = "activity";
public static final String FOREGROUND_EVENT = "foreground";
public static final String BACKGROUND_EVENT = "background";
public static final String AUTHORIZATION_EVENT = "authorization";
public static final String START_EVENT = "start";
public static final String STOP_EVENT = "stop";
public static final String ERROR_EVENT = "error";
private static final int PERMISSIONS_REQUEST_CODE = 1;
private BackgroundGeolocationFacade facade;
private org.slf4j.Logger logger;
public static class ErrorMap {
public static ReadableMap from(String message, int code) {
WritableMap out = Arguments.createMap();
out.putInt("code", code);
out.putString("message", message);
return out;
}
public static ReadableMap from(String message, Throwable cause, int code) {
WritableMap out = Arguments.createMap();
out.putInt("code", code);
out.putString("message", message);
out.putMap("cause", from(cause));
return out;
}
public static ReadableMap from(PluginException e) {
WritableMap out = Arguments.createMap();
out.putInt("code", e.getCode());
out.putString("message", e.getMessage());
if (e.getCause() != null) {
out.putMap("cause", from(e.getCause()));
}
return out;
}
private static WritableMap from(Throwable e) {
WritableMap out = Arguments.createMap();
out.putString("message", e.getMessage());
return out;
}
}
public BackgroundGeolocationModule(ReactApplicationContext reactContext) {
super(reactContext);
reactContext.addLifecycleEventListener(this);
facade = new BackgroundGeolocationFacade(getContext(), this);
logger = LoggerManager.getLogger(BackgroundGeolocationModule.class);
}
@Override
public String getName() {
return "BackgroundGeolocation";
}
/**
* Called when the activity will start interacting with the user.
*
*/
@Override
public void onHostResume() {
logger.info("App will be resumed");
facade.resume();
sendEvent(FOREGROUND_EVENT, null);
}
/**
* Called when the system is about to start resuming a previous activity.
*/
@Override
public void onHostPause() {
logger.info("App will be paused");
facade.pause();
sendEvent(BACKGROUND_EVENT, null);
}
/**
* The final call you receive before your activity is destroyed.
* Checks to see if it should turn off
*/
@Override
public void onHostDestroy() {
logger.info("Destroying plugin");
facade.destroy();
// facade = null;
}
private void runOnBackgroundThread(Runnable runnable) {
// currently react-native has no other thread we can run on
new Thread(runnable).start();
}
@ReactMethod
public void start() {
facade.start();
}
@ReactMethod
public void stop() {
facade.stop();
}
@ReactMethod
public void switchMode(Integer mode, Callback success, Callback error) {
facade.switchMode(mode);
}
@ReactMethod
public void configure(final ReadableMap options, final Callback success, final Callback error) {
runOnBackgroundThread(new Runnable() {
@Override
public void run() {
try {
Config config = ConfigMapper.fromMap(options);
facade.configure(config);
success.invoke(true);
} catch (JSONException e) {
logger.error("Configuration error: {}", e.getMessage());
error.invoke(ErrorMap.from("Configuration error", e, PluginException.CONFIGURE_ERROR));
} catch (PluginException e) {
logger.error("Configuration error: {}", e.getMessage());
error.invoke(ErrorMap.from(e));
}
}
});
}
@Deprecated // use checkStatus as replacement
@ReactMethod
public void isLocationEnabled(Callback success, Callback error) {
logger.debug("Location services enabled check");
try {
success.invoke(facade.locationServicesEnabled());
} catch (PluginException e) {
logger.error("Location service checked failed: {}", e.getMessage());
error.invoke(ErrorMap.from(e));
}
}
@ReactMethod
public void showLocationSettings() {
BackgroundGeolocationFacade.showLocationSettings(getContext());
}
@ReactMethod
public void showAppSettings() {
BackgroundGeolocationFacade.showAppSettings(getContext());
}
@ReactMethod
public void getStationaryLocation(Callback success, Callback error) {
BackgroundLocation stationaryLocation = facade.getStationaryLocation();
if (stationaryLocation != null) {
success.invoke(LocationMapper.toWriteableMap(stationaryLocation));
} else {
success.invoke();
}
}
@ReactMethod
public void getLocations(final Callback success, final Callback error) {
runOnBackgroundThread(new Runnable() {
public void run() {
WritableArray locationsArray = Arguments.createArray();
Collection<BackgroundLocation> locations = facade.getLocations();
for (BackgroundLocation location : locations) {
locationsArray.pushMap(LocationMapper.toWriteableMapWithId(location));
}
success.invoke(locationsArray);
}
});
}
@ReactMethod
public void getValidLocations(final Callback success, Callback error) {
runOnBackgroundThread(new Runnable() {
public void run() {
WritableArray locationsArray = Arguments.createArray();
Collection<BackgroundLocation> locations = facade.getValidLocations();
for (BackgroundLocation location : locations) {
locationsArray.pushMap(LocationMapper.toWriteableMapWithId(location));
}
success.invoke(locationsArray);
}
});
}
@ReactMethod
public void deleteLocation(final Integer locationId, final Callback success, Callback error) {
runOnBackgroundThread(new Runnable() {
public void run() {
facade.deleteLocation(locationId.longValue());
success.invoke(true);
}
});
}
@ReactMethod
public void deleteAllLocations(final Callback success, Callback error) {
runOnBackgroundThread(new Runnable() {
public void run() {
facade.deleteAllLocations();
success.invoke(true);
}
});
}
@ReactMethod
public void getCurrentLocation(final ReadableMap options, final Callback success, final Callback error) {
try {
int timeout = options.hasKey("timeout") ? options.getInt("timeout") : Integer.MAX_VALUE;
long maximumAge = options.hasKey("maximumAge") ? options.getInt("maximumAge") : Long.MAX_VALUE;
boolean enableHighAccuracy = options.hasKey("enableHighAccuracy") ? options.getBoolean("enableHighAccuracy") : false;
BackgroundLocation location = facade.getCurrentLocation(timeout, maximumAge, enableHighAccuracy);
success.invoke(LocationMapper.toWriteableMap(location));
} catch (PluginException e) {
error.invoke(ErrorMap.from(e));
}
}
@ReactMethod
public void getConfig(final Callback success, final Callback error) {
runOnBackgroundThread(new Runnable() {
public void run() {
try {
Config config = facade.getConfig();
ReadableMap out = ConfigMapper.toMap(config);
success.invoke(out);
} catch (PluginException e) {
logger.error("Error getting config: {}", e.getMessage());
error.invoke(ErrorMap.from(e));
}
}
});
}
@ReactMethod
public void getLogEntries(final Integer limit, final Integer offset, final String minLevel, final Callback success, final Callback error) {
runOnBackgroundThread(new Runnable() {
public void run() {
WritableArray logEntriesArray = Arguments.createArray();
Collection<LogEntry> logEntries = facade.getLogEntries(limit, offset, minLevel);
for (LogEntry logEntry : logEntries) {
WritableMap out = Arguments.createMap();
out.putInt("id", logEntry.getId());
out.putInt("context", logEntry.getContext());
out.putString("level", logEntry.getLevel());
out.putString("message", logEntry.getMessage());
out.putString("timestamp", new Long(logEntry.getTimestamp()).toString());
out.putString("logger", logEntry.getLoggerName());
if (logEntry.hasStackTrace()) {
out.putString("stackTrace", logEntry.getStackTrace());
}
logEntriesArray.pushMap(out);
}
success.invoke(logEntriesArray);
}
});
}
@ReactMethod
public void checkStatus(final Callback success, final Callback error) {
runOnBackgroundThread(new Runnable() {
public void run() {
try {
WritableMap out = Arguments.createMap();
out.putBoolean("isRunning", facade.isRunning());
out.putBoolean("hasPermissions", facade.hasPermissions()); //@Deprecated
out.putBoolean("locationServicesEnabled", facade.locationServicesEnabled());
out.putInt("authorization", getAuthorizationStatus());
success.invoke(out);
} catch (PluginException e) {
logger.error("Location service checked failed: {}", e.getMessage());
error.invoke(ErrorMap.from(e));
}
}
});
}
@ReactMethod
public void headlessTask(String jsFunction, Callback success, Callback error) {
logger.debug("Registering headless task");
facade.registerHeadlessTask(jsFunction);
success.invoke();
}
@ReactMethod
public void forceSync(Callback success, Callback error) {
facade.forceSync();
success.invoke();
}
private void sendEvent(String eventName, Object params) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
private void sendError(PluginException error) {
WritableMap out = Arguments.createMap();
out.putInt("code", error.getCode());
out.putString("message", error.getMessage());
sendEvent(ERROR_EVENT, out);
}
private void sendError(int code, String message) {
WritableMap out = Arguments.createMap();
out.putInt("code", code);
out.putString("message", message);
sendEvent(ERROR_EVENT, out);
}
public int getAuthorizationStatus() {
return facade.getAuthorizationStatus();
}
public Context getContext() {
return getReactApplicationContext().getBaseContext();
}
@Override
public void onAuthorizationChanged(int authStatus) {
sendEvent(AUTHORIZATION_EVENT, authStatus);
}
@Override
public void onLocationChanged(BackgroundLocation location) {
sendEvent(LOCATION_EVENT, LocationMapper.toWriteableMapWithId(location));
}
@Override
public void onStationaryChanged(BackgroundLocation location) {
sendEvent(STATIONARY_EVENT, LocationMapper.toWriteableMapWithId(location));
}
@Override
public void onActitivyChanged(BackgroundActivity activity) {
WritableMap out = Arguments.createMap();
out.putInt("confidence", activity.getConfidence());
out.putString("type", BackgroundActivity.getActivityString(activity.getType()));
sendEvent(ACTIVITY_EVENT, out);
}
@Override
public void onServiceStatusChanged(int status) {
switch (status) {
case LocationService.SERVICE_STARTED:
sendEvent(START_EVENT, null);
return;
case LocationService.SERVICE_STOPPED:
sendEvent(STOP_EVENT, null);
return;
}
}
@Override
public void onError(PluginException error) {
sendError(error);
}
}