我如何在我的后台服务 (android) 中使用一个 Angular http 客户端。
我的应用需要将数据从后台服务发送到我的服务器。
我正在使用 NativeScript/Angular。
我的后台服务
declare var android;
if (application.android) {
(<any>android.app.Service).extend("org.tinus.Example.BackgroundService", {
onStartCommand: function (intent, flags, startId) {
this.super.onStartCommand(intent, flags, startId);
return android.app.Service.START_STICKY;
},
onCreate: function () {
let that = this;
geolocation.enableLocationRequest().then(function () {
that.id = geolocation.watchLocation(
function (loc) {
if (loc) {
// should send to server from here
}
},
function (e) {
console.log("Background watchLocation error: " + (e.message || e));
},
{
desiredAccuracy: Accuracy.high,
updateDistance: 5,
updateTime: 5000,
minimumUpdateTime: 100
});
}, function (e) {
console.log("Background enableLocationRequest error: " + (e.message || e));
});
},
onBind: function (intent) {
console.log("on Bind Services");
},
onUnbind: function (intent) {
console.log('UnBind Service');
},
onDestroy: function () {
geolocation.clearWatch(this.id);
}
});
}
我尝试了两种方法。
(1)。使用 Injector 注入(inject)我的服务
const injector = Injector.create([ { provide: ExampleService, useClass: ExampleService, deps: [HttpClient] }]);
const service = injector.get(ExampleService);
console.log(service.saveDriverLocation); // This prints
service.saveDriverLocation(new GeoLocation(loc.latitude, loc.longitude, loc.horizontalAccuracy, loc.altitude), ['id']); // This complains
问题 (1)
System.err: TypeError: Cannot read property 'post' of undefined
(2)。使用 native 代码
let url = new java.net.URL("site/fsc");
let connection = null;
try {
connection = url.openConnection();
} catch (error) {
console.log(error);
}
connection.setRequestMethod("POST");
let out = new java.io.BufferedOutputStream(connection.getOutputStream());
let writer = new java.io.BufferedWriter(new java.io.OutputStreamWriter(out, "UTF-8"));
let data = 'mutation NewDriverLoc{saveDriverLocation(email:"' + (<SystemUser>JSON.parse(getString('User'))).email + '",appInstanceId:' + (<ApplicationInstance>JSON.parse(getString('appInstance'))).id + ',geoLocation:{latitude:' + loc.latitude + ',longitude:' + loc.longitude + ',accuracy:' + loc.horizontalAccuracy + '}){id}}';
writer.write(data);
writer.flush();
writer.close();
out.close();
connection.connect();
(2) 的问题
System.err: Caused by: android.os.NetworkOnMainThreadException
所以基本上第一种方法是 Angular ,问题是我没有注入(inject)所有需要的服务/不确定如何注入(inject)。
第二种方法是原生的,问题是网络在主线程上。我需要使用 AsyncTask 只是不确定如何使用
最佳答案
请看这个链接 How do I fix android.os.NetworkOnMainThreadException?
将以下内容添加到您在选项 2 中提到的 native 代码中。它应该可以工作
let policy = new
android.os.StrictMode.ThreadPolicy.Buiilder().permitAll().build();
andriod.os.StrictMode.setThreadPolicy(policy);
关于android - 如何在 native 后台服务中使用( Angular )HTTP 客户端 - NativeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50904135/