Skip to content
This repository was archived by the owner on Nov 8, 2023. It is now read-only.

Commit 2c59ee1

Browse files
fix: Clear watchers on "application exit" on API 26 and above
1 parent a945cd1 commit 2c59ee1

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

demo/app/background-service.ts

+10-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@ import * as application from "tns-core-modules/application";
44
import { device } from "tns-core-modules/platform";
55
import * as Toast from "nativescript-toast";
66

7+
let watchId;
8+
application.on(application.exitEvent, function (args: any) {
9+
if (watchId) {
10+
geolocation.clearWatch(watchId);
11+
}
12+
});
13+
714
if (application.android) {
815
if (device.sdkVersion < "26") {
916
(<any>android.app.Service).extend("com.nativescript.location.BackgroundService", {
@@ -50,10 +57,9 @@ if (application.android) {
5057
else {
5158
(<any>android.app).job.JobService.extend("com.nativescript.location.BackgroundService26", {
5259
onStartJob(params) {
53-
let that = this;
5460
let executed = false;
5561
geolocation.enableLocationRequest().then(function () {
56-
that.id = geolocation.watchLocation(
62+
watchId = geolocation.watchLocation(
5763
function (loc) {
5864
if (loc) {
5965
let toast = Toast.makeText('Background Location: ' + loc.latitude + ' ' + loc.longitude);
@@ -80,7 +86,8 @@ if (application.android) {
8086
},
8187

8288
onStopJob() {
83-
geolocation.clearWatch(this.id);
89+
console.log('service onStopJob');
90+
geolocation.clearWatch(watchId);
8491
return true;
8592
},
8693
});

demo/app/main-page.ts

+10
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,16 @@ let watchIds = [];
1515
let backgroundIds = [];
1616
declare var com: any;
1717

18+
application.on(application.exitEvent, function (args: any) {
19+
if (application.android && backgroundIds.length > 0) {
20+
let context = utils.ad.getApplicationContext();
21+
const jobScheduler = context.getSystemService((<any>android.content.Context).JOB_SCHEDULER_SERVICE);
22+
const service = backgroundIds.pop();
23+
jobScheduler.cancel(service);
24+
console.log(`Job Canceled: ${service}`);
25+
}
26+
});
27+
1828
export function pageLoaded(args: EventData) {
1929
page = <Page>args.object;
2030
page.bindingContext = model;

0 commit comments

Comments
 (0)