This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
geolocation.android.ts
394 lines (346 loc) · 15.8 KB
/
geolocation.android.ts
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
import { on as applicationOn, android as androidAppInstance, AndroidApplication, uncaughtErrorEvent, UnhandledErrorEventData } from "application";
import { Accuracy } from "tns-core-modules/ui/enums";
import { setTimeout, clearTimeout } from "tns-core-modules/timer";
import { LocationBase, defaultGetLocationTimeout, fastestTimeUpdate, minTimeUpdate } from "./geolocation.common";
import { Options, successCallbackType, errorCallbackType } from "./location-monitor";
import * as permissions from "nativescript-permissions";
declare var com: any;
let REQUEST_ENABLE_LOCATION = 4269; // random number
let _onEnableLocationSuccess = null;
let _onEnableLocationFail = null;
const locationListeners = {};
let watchIdCounter = 0;
let fusedLocationClient;
let attachedForErrorHandling = false;
function _ensureLocationClient() {
// Wrapped in a function as we should not access java object there because of the snapshots.
fusedLocationClient = fusedLocationClient ||
com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(androidAppInstance.context);
}
androidAppInstance.on(AndroidApplication.activityResultEvent, function (args: any) {
if (args.requestCode === REQUEST_ENABLE_LOCATION) {
if (args.resultCode === 0) {
if (_onEnableLocationFail) {
_onEnableLocationFail("Location not enabled.");
}
} else if (_onEnableLocationSuccess) {
_onEnableLocationSuccess();
}
}
});
function isAirplaneModeOn(): boolean {
return android.provider.Settings.System.getInt(androidAppInstance.context.getContentResolver(),
android.provider.Settings.System.AIRPLANE_MODE_ON) !== 0;
}
function isProviderEnabled(provider: string): boolean {
try {
const locationManager: android.location.LocationManager = (<android.content.Context>androidAppInstance.context)
.getSystemService(android.content.Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(provider);
} catch (ex) {
return false;
}
}
function errorHandler(errData: UnhandledErrorEventData) {
while (watchIdCounter !== 0) {
clearWatch(watchIdCounter);
watchIdCounter--;
}
}
export function getCurrentLocation(options: Options): Promise<Location> {
return new Promise(function (resolve, reject) {
enableLocationRequest().then(() => {
if (options.timeout === 0) {
// get last known
LocationManager.getLastLocation(options.maximumAge, resolve, reject);
} else {
// wait for the exact location
let locationRequest = _getLocationRequest(options);
let watchId = _getNextWatchId();
let locationCallback = _getLocationCallback(watchId, (nativeLocation) => {
clearWatch(watchId);
resolve(new Location(nativeLocation));
});
LocationManager.requestLocationUpdates(locationRequest, locationCallback);
const timerId = setTimeout(function () {
clearWatch(watchId);
clearTimeout(timerId);
reject(new Error("Timeout while searching for location!"));
}, options.timeout || defaultGetLocationTimeout);
}
}, reject);
});
}
function _getNextWatchId() {
let watchId = ++watchIdCounter;
return watchId;
}
function _getLocationCallback(watchId, onLocation): any {
let LocationCallback = com.google.android.gms.location.LocationCallback.extend({
// IMPORTANT: Do not touch any scope variables here. The Java definition of the class is cached
// internally in NativeScript and if we directly use 'watchId' or 'onLocation' here, we will
// always receive the references from the first '_getLocationCallback' method call!!!
onLocationResult: function (locationResult) {
this.onLocation(locationResult.getLastLocation());
}
});
let locationCallback = new LocationCallback();
// Workaround for the above-mentioned Note
locationCallback.onLocation = onLocation;
locationListeners[watchId] = locationCallback;
return locationCallback;
}
function _getLocationRequest(options: Options): any {
let mLocationRequest = new com.google.android.gms.location.LocationRequest();
let updateTime = options.updateTime === 0 ? 0 : options.updateTime || minTimeUpdate;
mLocationRequest.setInterval(updateTime);
let minUpdateTime = options.minimumUpdateTime === 0 ?
0 : options.minimumUpdateTime || Math.min(updateTime, fastestTimeUpdate);
mLocationRequest.setFastestInterval(minUpdateTime);
if (options.updateDistance) {
mLocationRequest.setSmallestDisplacement(options.updateDistance);
}
if (options.desiredAccuracy === Accuracy.high) {
mLocationRequest.setPriority(com.google.android.gms.location.LocationRequest.PRIORITY_HIGH_ACCURACY);
} else {
mLocationRequest.setPriority(com.google.android.gms.location.LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
return mLocationRequest;
}
function _requestLocationPermissions(): Promise<any> {
return new Promise<any>(function (resolve, reject) {
if (LocationManager.shouldSkipChecks()) {
resolve();
} else {
permissions.requestPermission((<any>android).Manifest.permission.ACCESS_FINE_LOCATION).then(resolve, reject);
}
});
}
function _getLocationListener(maxAge, onLocation, onError) {
return _getTaskSuccessListener((nativeLocation: android.location.Location) => {
if (nativeLocation != null) {
let location = new Location(nativeLocation);
if (typeof maxAge === "number" && nativeLocation != null) {
if (location.timestamp.valueOf() + maxAge > new Date().valueOf()) {
onLocation(location);
} else {
onError(new Error("Last known location too old!"));
}
} else {
onLocation(location);
}
} else {
onError(new Error("There is no last known location!"));
}
});
}
function _getTaskSuccessListener(done: (result) => void) {
return new com.google.android.gms.tasks.OnSuccessListener({
onSuccess: done
});
}
function _getTaskFailListener(done: (exception) => void) {
return new com.google.android.gms.tasks.OnFailureListener({
onFailure: done
});
}
export function watchLocation(successCallback: successCallbackType, errorCallback: errorCallbackType, options: Options): number {
// wrap in zoned callback in order to avoid UI glitches in Angular applications
// check https://github.com/NativeScript/NativeScript/issues/2229
const zonedSuccessCallback = zonedCallback(successCallback);
const zonedErrorCallback = zonedCallback(errorCallback);
if ((!permissions.hasPermission((<any>android).Manifest.permission.ACCESS_FINE_LOCATION) ||
!_isGooglePlayServicesAvailable()) && !LocationManager.shouldSkipChecks()) {
throw new Error('Cannot watch location. Call "enableLocationRequest" first');
}
if (!attachedForErrorHandling) {
attachedForErrorHandling = true;
applicationOn(uncaughtErrorEvent, errorHandler.bind(this));
}
let locationRequest = _getLocationRequest(options);
let watchId = _getNextWatchId();
const locationCallback = _getLocationCallback(watchId, (nativeLocation) => {
zonedSuccessCallback(new Location(nativeLocation));
});
LocationManager.requestLocationUpdates(locationRequest, locationCallback);
return watchId;
}
export function clearWatch(watchId: number): void {
let listener = locationListeners[watchId];
if (listener) {
LocationManager.removeLocationUpdates(listener);
delete locationListeners[watchId];
}
}
export function enableLocationRequest(always?: boolean): Promise<void> {
return new Promise<void>(function (resolve, reject) {
_requestLocationPermissions().then(() => {
_makeGooglePlayServicesAvailable().then(() => {
_isLocationServiceEnabled().then(() => {
resolve();
}, (ex) => {
if (typeof ex.getStatusCode === "function") {
const statusCode = ex.getStatusCode();
if (statusCode === com.google.android.gms.location.LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
try {
// cache resolve and reject callbacks in order to call them
// on REQUEST_ENABLE_LOCATION Activity Result
_onEnableLocationSuccess = resolve;
_onEnableLocationFail = reject;
return ex.startResolutionForResult(androidAppInstance.foregroundActivity, REQUEST_ENABLE_LOCATION);
} catch (sendEx) {
// Ignore the error.
return resolve();
}
} else if (statusCode === com.google.android.gms.location.LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE
&& isAirplaneModeOn()
&& isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
return resolve();
}
}
reject(new Error("Cannot enable the location service. " + ex));
});
}, reject);
}, reject);
});
}
function _makeGooglePlayServicesAvailable(): Promise<void> {
return new Promise<void>(function (resolve, reject) {
if (_isGooglePlayServicesAvailable()) {
resolve();
return;
}
let googleApiAvailability = com.google.android.gms.common.GoogleApiAvailability.getInstance();
googleApiAvailability.makeGooglePlayServicesAvailable(androidAppInstance.foregroundActivity)
.addOnSuccessListener(_getTaskSuccessListener(resolve))
.addOnFailureListener(_getTaskFailListener(reject));
});
}
function _isGooglePlayServicesAvailable(): boolean {
if (LocationManager.shouldSkipChecks()) {
return true;
}
let isLocationServiceEnabled = true;
let googleApiAvailability = com.google.android.gms.common.GoogleApiAvailability.getInstance();
let resultCode = googleApiAvailability.isGooglePlayServicesAvailable(androidAppInstance.context);
if (resultCode !== com.google.android.gms.common.ConnectionResult.SUCCESS) {
isLocationServiceEnabled = false;
}
return isLocationServiceEnabled;
}
function _isLocationServiceEnabled(options?: Options): Promise<boolean> {
return new Promise(function (resolve, reject) {
if (LocationManager.shouldSkipChecks()) {
resolve(true);
return;
}
options = options || { desiredAccuracy: Accuracy.high, updateTime: 0, updateDistance: 0, maximumAge: 0, timeout: 0 };
let locationRequest = _getLocationRequest(options);
let locationSettingsBuilder = new com.google.android.gms.location.LocationSettingsRequest.Builder();
locationSettingsBuilder.addLocationRequest(locationRequest);
locationSettingsBuilder.setAlwaysShow(true);
let locationSettingsClient = com.google.android.gms.location.LocationServices.getSettingsClient(androidAppInstance.context);
locationSettingsClient.checkLocationSettings(locationSettingsBuilder.build())
.addOnSuccessListener(_getTaskSuccessListener(resolve))
.addOnFailureListener(_getTaskFailListener(reject));
});
}
export function isEnabled(options?: Options): Promise<boolean> {
return new Promise(function (resolve, reject) {
if (!_isGooglePlayServicesAvailable() ||
!permissions.hasPermission((<any>android).Manifest.permission.ACCESS_FINE_LOCATION)) {
resolve(false);
} else {
_isLocationServiceEnabled(options).then(
() => {
resolve(true);
}, (ex) => {
if (typeof ex.getStatusCode === "function"
&& ex.getStatusCode() === com.google.android.gms.location.LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE
&& isAirplaneModeOn()
&& isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
return resolve(true);
}
resolve(false);
});
}
});
}
export function distance(loc1: Location, loc2: Location): number {
if (!loc1.android) {
loc1.android = androidLocationFromLocation(loc1);
}
if (!loc2.android) {
loc2.android = androidLocationFromLocation(loc2);
}
return loc1.android.distanceTo(loc2.android);
}
function androidLocationFromLocation(location: Location): android.location.Location {
let androidLocation = new android.location.Location("custom");
androidLocation.setLatitude(location.latitude);
androidLocation.setLongitude(location.longitude);
if (location.altitude) {
androidLocation.setAltitude(location.altitude);
}
if (location.speed) {
androidLocation.setSpeed(float(location.speed));
}
if (location.direction) {
androidLocation.setBearing(float(location.direction));
}
if (location.timestamp) {
try {
androidLocation.setTime(long(location.timestamp.getTime()));
} catch (e) {
console.error("invalid location timestamp");
}
}
return androidLocation;
}
// abstraction for unit testing
export class LocationManager {
static getLastLocation(maximumAge, resolve, reject): Promise<Location> {
_ensureLocationClient();
return fusedLocationClient.getLastLocation()
.addOnSuccessListener(_getLocationListener(maximumAge, resolve, reject))
.addOnFailureListener(_getTaskFailListener((e) => reject(new Error(e.getMessage()))));
}
static requestLocationUpdates(locationRequest, locationCallback): void {
_ensureLocationClient();
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null /* Looper */);
}
static removeLocationUpdates(listener) {
_ensureLocationClient();
fusedLocationClient.removeLocationUpdates(listener);
}
static shouldSkipChecks(): boolean {
return false;
}
static setMockLocationManager(MockLocationManager) {
LocationManager.getLastLocation = MockLocationManager.getLastLocation;
LocationManager.requestLocationUpdates = MockLocationManager.requestLocationUpdates;
LocationManager.removeLocationUpdates = MockLocationManager.removeLocationUpdates;
LocationManager.shouldSkipChecks = MockLocationManager.shouldSkipChecks;
}
}
export class Location extends LocationBase {
public android: android.location.Location; // android Location
constructor(androidLocation: android.location.Location) {
super();
if (androidLocation) {
this.android = androidLocation;
this.latitude = androidLocation.getLatitude();
this.longitude = androidLocation.getLongitude();
this.altitude = androidLocation.getAltitude();
this.horizontalAccuracy = androidLocation.getAccuracy();
this.verticalAccuracy = androidLocation.getAccuracy();
this.speed = androidLocation.getSpeed();
this.direction = androidLocation.getBearing();
this.timestamp = new Date(androidLocation.getTime());
}
}
}
// used from unit tests
export function setCustomLocationManager(MockLocationManager) {
LocationManager.setMockLocationManager(MockLocationManager);
}