How can i use an angular http client in my background service (android).
My app needs to send the data from the background service to my server.
Im using NativeScript / Angular.
My Background Service
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);
}
});
}
Two approaches i tried.
(1). Using Injector to inject my service
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
Issue for (1)
System.err: TypeError: Cannot read property 'post' of undefined
(2). Using Native code
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();
Issue for (2)
System.err: Caused by: android.os.NetworkOnMainThreadException
So basically the first approach is angular, issue is that im not injecting all the needed services / not sure how.
Second approach is native, and the issue is the network is on the main thread. I need to use AsyncTask just not sure how