我正在使用此地理位置插件(https://github.com/NativeScript/nativescript-geolocation/tree/e125998c07ced42a215aca1a8feac1b7dbe7b6d6)在后台运行应用程序时不断获取位置更新。
我尝试在演示中使用代码,但是我没有弄清楚如何使其工作。
即使应用程序在后台运行,我仍希望用户按下按钮,然后该应用程序开始监视其位置。
home.component.ts
import { Component, OnInit, AfterViewInit } from "@angular/core";
import { RadSideDrawer } from "nativescript-ui-sidedrawer";
import { getRootView } from "tns-core-modules/application";
import * as app from "tns-core-modules/application";
const utils = require("tns-core-modules/utils/utils");
import { device } from "tns-core-modules/platform";
//import { GeolocationService } from "../services/geolocation/geolocation.service";
@Component({
selector: "Home",
moduleId: module.id,
templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
public drawer: RadSideDrawer;
public buttonText = "Start";
locations = [];
watchIds = [];
jobId = 308;
constructor(
public geolocationService: GeolocationService,
) {}
ngOnInit(): void {
app.on(app.exitEvent, this._stopBackgroundJob);
}
ngAfterViewInit() {
this.drawer = <RadSideDrawer>getRootView();
this.drawer.gesturesEnabled = true;
}
onDrawerButtonTap(): void {
const sideDrawer = <RadSideDrawer>app.getRootView();
sideDrawer.showDrawer();
}
_stopBackgroundJob() {
if (app.android) {
let context = utils.ad.getApplicationContext();
const jobScheduler = context.getSystemService((<any>android.content.Context).JOB_SCHEDULER_SERVICE);
if (jobScheduler.getPendingJob(this.jobId) !== null) {
jobScheduler.cancel(this.jobId);
console.log(`Job Canceled: ${this.jobId}`);
}
}
}
checkLoc(){
this.geolocationService.buttonGetLocationTap()
}
_onGeolocationService(){
this.geolocationService.enableLocation()
.then(result => {
this.geolocationService.monitorLocation();
if(this.geolocationService.locationMonitor === true){
this.buttonText = "Stop";
} else {
this.buttonText = "Start";
}
})
}
public startBackgroundTap() {
if (app.android) {
let context = utils.ad.getApplicationContext();
if (device.sdkVersion >= "26") {
const jobScheduler = context.getSystemService((<any>android.content.Context).JOB_SCHEDULER_SERVICE);
const component = new android.content.ComponentName(context, com.nativescript.location.BackgroundService26.class);
const builder = new (<any>android.app).job.JobInfo.Builder(this.jobId, component);
builder.setOverrideDeadline(0);
return jobScheduler.schedule(builder.build());
} else {
let intent = new android.content.Intent(context, com.nativescript.location.BackgroundService.class);
context.startService(intent);
}
}
}
public stopBackgroundTap() {
if (app.android) {
if (device.sdkVersion >= "26") {
this._stopBackgroundJob();
} else {
let context = utils.ad.getApplicationContext();
let intent = new android.content.Intent(context, com.nativescript.location.BackgroundService.class);
context.stopService(intent);
}
}
}
}
geolocation.service.ts
import { Injectable } from '@angular/core';
import * as geolocation from "nativescript-geolocation";
import { Accuracy } from "tns-core-modules/ui/enums";
@Injectable({
providedIn: 'root'
})
export class GeolocationService {
locations= [];
watchIds = [];
constructor() { }
public enableLocation() {
return geolocation.enableLocationRequest();
}
public checkIfLocationIsEnabled() {
geolocation.isEnabled()
.then(function (isEnabled) {
if(isEnabled) {
return true;
} else {
return false;
}
})
}
public buttonGetLocationTap() {
let that = this;
geolocation.getCurrentLocation({
desiredAccuracy: Accuracy.high,
iosAllowsBackgroundLocationUpdates: true,
iosPausesLocationUpdatesAutomatically: false,
iosOpenSettingsIfLocationHasBeenDenied: true,
maximumAge: 5000,
timeout: 10000,
updateTime: 10000,
}).then(function (loc) {
console.log(loc["latitude"], loc["longitude"])
if (loc) {
that.locations.push(loc);
}
}, function (e) {
console.log("Error: " + (e.message || e));
});
}
public buttonStartTap() {
try {
let that = this;
that.watchIds.push(geolocation.watchLocation(
function (loc) {
if (loc) {
that.locations.push(loc);
}
},
function (e) {
console.log("Error: " + e.message);
},
{
desiredAccuracy: Accuracy.high,
iosAllowsBackgroundLocationUpdates: true,
iosPausesLocationUpdatesAutomatically: false,
iosOpenSettingsIfLocationHasBeenDenied: true,
maximumAge: 7000,
timeout: 9000,
updateTime: 9000,
}));
} catch (ex) {
console.log("Error: " + ex.message);
}
}
public buttonStopTap() {
let watchId = this.watchIds.pop();
while (watchId != null) {
geolocation.clearWatch(watchId);
watchId = this.watchIds.pop();
}
}
public buttonClearTap() {
this.locations.splice(0, this.locations.length);
}
}
background.service.ts
import * as geolocation from "nativescript-geolocation";
import { Accuracy } from "tns-core-modules/ui/enums";
import * as application from "tns-core-modules/application";
import { device } from "tns-core-modules/platform";
let watchId;
function _clearWatch() {
if (watchId) {
geolocation.clearWatch(watchId);
watchId = null;
}
}
function _startWatch() {
geolocation.enableLocationRequest().then(function () {
_clearWatch();
watchId = geolocation.watchLocation(
function (loc) {
if (loc) {
console.log('Background Location: ' + loc.latitude + ' ' + loc.longitude);
}
},
function (e) {
console.log("Background watchLocation error: " + (e.message || e));
},
{
desiredAccuracy: Accuracy.high,
updateDistance: 1.0,
updateTime: 3000,
minimumUpdateTime: 100
});
}, function (e) {
console.log("Background enableLocationRequest error: " + (e.message || e));
});
}
application.on(application.exitEvent, _clearWatch);
if (application.android) {
if (device.sdkVersion < "26") {
(<any>android.app.Service).extend("com.nativescript.location.BackgroundService", {
onStartCommand: function (intent, flags, startId) {
this.super.onStartCommand(intent, flags, startId);
return android.app.Service.START_STICKY;
},
onCreate: function () {
_startWatch();
},
onBind: function (intent) {
console.log("on Bind Services");
},
onUnbind: function (intent) {
console.log('UnBind Service');
},
onDestroy: function () {
console.log('service onDestroy');
_clearWatch();
}
});
} else {
(<any>android.app).job.JobService.extend("com.nativescript.location.BackgroundService26", {
onStartJob() {
console.log('service onStartJob');
_startWatch();
return true;
},
onStopJob(jobParameters: any) {
console.log('service onStopJob');
this.jobFinished(jobParameters, false);
_clearWatch();
return false;
},
});
}
}
首先,'com'名称空间存在问题,因为它说“类型'comof'上不存在属性'nativescript'”。问题出现在以下三行的home.component.ts中:
const component = new android.content.ComponentName(context,com.nativescript.location.BackgroundService26.class); let intent = new android.content.Intent(context,com.nativescript.location.BackgroundService.class); let intent = new android.content.Intent(context,com.nativescript.location.BackgroundService.class);
第二,我不知道后台服务的目的是什么,因为我没有在演示中的任何地方使用它(或者也许是,但是我不熟悉)。
谢谢!
答案 0 :(得分:1)
“属性'nativescript'在'typeof com'类型上不存在“
这是简单的TypeScript声明错误,将其强制转换为任何类型都可以解决您的问题。
const component = new android.content.ComponentName(context, (com as any).nativescript.location.BackgroundService26.class);
let intent = new android.content.Intent(context, (com as any).nativescript.location.BackgroundService.class);
let intent = new android.content.Intent(context, (com as any).nativescript.location.BackgroundService.class);
正如您在演示应用程序中看到的那样,declare var com: any;
具有相同的目的。另外,如果您熟悉TypeScript,则可以声明正确的类型。
第二,我不知道后台服务的目的是什么
我认为我们已经在另一个线程中对此进行了讨论,即使您的应用未运行,当您要运行某些任务时,也会使用后台服务。
您在com.nativescript.location.BackgroundService
上方使用的类来自该文件(background-service.ts
)。同样的类也应该在AndroidManifest.xml中声明。
编辑:
听起来好像您没有通过输入webpack.config.js
文件来更新background-service.ts
。
// Add your custom Activities, Services and other Android app components here.
const appComponents = [
"tns-core-modules/ui/frame",
"tns-core-modules/ui/frame/activity",
resolve(__dirname, "src/path/to/background-service"),
];