我正在开发应用程序后台服务,以在后台模式下连续获取位置经度。使用的cordova插件,即添加的插件是cordova插件添加https://github.com/pmwisdom/cordova-background-geolocation-services.git。
即使该应用被终止,我也希望让服务在后台运行。 “杀死”是指长按主页按钮->查看所有正在运行的应用程序->将我的应用程序滑到一旁->应用程序被杀死,或者长按后退按钮->应用程序被杀死
我的代码如下。
CDVBackgroundLocationServices.swift()
var msg = "Got Location Update: { \(latitude) - \(longitude) } Accuracy: \(accuracy) speed: \(speed)";
if(useActivityDetection) {
msg += " Stationary : \(activityManager.isStationary)";
}
log(message: msg);
locationCommandDelegate?.run(inBackground: {
var result:CDVPluginResult?;
let loc = self.locationToDict(loc: bestLocation!) as [NSObject: AnyObject];
result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs:loc);
result!.setKeepCallbackAs(true);
locationCommandDelegate?.send(result, callbackId:locationUpdateCallback);
});
let urlToRequest = "c=mt90&a=tracker";
let url4 = URL(string: urlToRequest)!
let session4 = URLSession.shared
let request = NSMutableURLRequest(url: url4)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let speedOptionalString:String?
speedOptionalString = "\(speed)"
let respSpeed = "-1"
var makeSpeed="0";
if var respSpeed = speedOptionalString {
makeSpeed = "0"
}else{
makeSpeed = "\(speed)"
}
let requestData = [
"UUID":"\(deviceImei)",
"Latitude": "\(latitude)" ,
"Longitude": "\(longitude)" ,
"speed": "\(makeSpeed)",
] as [String : String]
request.httpBody = try! JSONEncoder().encode(requestData)
let task = session4.dataTask(with: request as URLRequest) { (data, response, error) in
guard let _: Data = data, let _: URLResponse = response, error == nil else {
return
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("*****This is the data 4: \(dataString)") //JSONSerialization
}
task.resume()
}
DeviceReady()
Msgs.Config.timeInterval=localStorage.getItem('timeInterval');
Msgs.Config.deviceId = device.uuid;
//Get plugin
bgLocationServices = window.plugins.backgroundLocationServices;
var timeInterval=Msgs.Config.timeInterval*1000;
bgLocationServices.configure({
//Both
desiredAccuracy: 20,
distanceFilter: 5,
debug: true,
interval: timeInterval,
useActivityDetection: true
Msgs.Config.deviceId,
});
bgLocationServices.start();
打开应用程序后,我看到该服务正在运行。通过主页按钮最小化应用程序时,它仍在运行。通过后退按钮关闭应用程序时,它仍在运行。但是,如果我如上所述杀死它,它将停止。我该如何解决?