Geolocation reporting in Ionic app Background - android

I intend to get users geolocation even when the app sits dormant in the background and store the same in the database.
I'm using katzer's Cordova Background Plug-in,
When I try to access navigator.geolocation.getCurrentPosition inside backgroundMode.onactivate function, nothing happens, Whereas when I try passing hard coded values api is called, data is stored in database.
following is my code
document.addEventListener('deviceready', function() {
// Android customization
cordova.plugins.backgroundMode.setDefaults({
text: 'Doing heavy tasks.'
});
// Enable background mode
cordova.plugins.backgroundMode.enable();
// Called when background mode has been activated
cordova.plugins.backgroundMode.onactivate = function() {
console.log('inside background')
a();
}
var a = function() {
console.log('a called')
navigator.geolocation.getCurrentPosition(function(pos) {
console.log('inside navigate');
var data = {
Lati: '123456',
Longi: '132456',
//LoginID: JSON.parse(window.localStorage.getItem('LoginId'))
EmpCode: localStorage.getItem('LoginId')
};
$http.post("https://app.sbismart.com/bo/ContactManagerApi/UpdateEmployeeLoc", data).success(function(rsdata, status) {
console.log('inside rsdata');
console.log(data.Lati + "," + data.Longi);
})
}, function(error) {
alert('Unable to get location: ' + error.message);
});
}
}, false);

cordova.plugins.backgroundMode.onfailure = function(errorCode) {
console.log(errorCode)
};`
and check as to why is it failing....then again u need to run the locationService function in a timeout function in the background to get updated about the location and check the location from previously got location.
Something like this...
cordova.plugins.backgroundMode.onactivate = function () {
setTimeout(function () {
a();
}, 5000);
}
Hope this helps.

Related

Why doesn't the cordova-plugin-background-mode plugin work on android?

I'm trying to send the geolocation by ajax in intervals of 30 seconds in the background, since this application is being used to know the "real time" location of the deliverers at all times. The problem is that when you enable the plugin in the android version when generating the apk and installing it on the cell phone it doesn't work, even when you put the application in the background and put it back in the foreground it restarts completely.
These are the versions that I am using for the development of the application:
Cordova 10
Nodejs 14.16
JQuery 3.5
Structure:
js
login.js
home.js
index.html -- this is the login page where the login.js file is located
home.html -- this is the home page where the home.js file is located
login.js
document.addEventListener('deviceready', function () {
cordova.plugins.backgroundMode.enable();
});
home.js
let isSending = false;
let intervalId = null;
let email = window.localStorage.getItem("user_email");
let token = window.localStorage.getItem("token");
let path = window.localStorage.getItem("api_url");
let onMapSuccess = function (position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
if (!isSending) {
$.ajax({
type: "GET",
url: path + "/geoTransportista/" + email + "/" + latitude + "/" + longitude,
headers: {
Authorization: "Bearer " + token,
"Content-type": "application/json",
},
beforeSend: function() {
isSending = true;
}
}).done((res) => {
if (res.state == "successful") console.log("ENVIO EXITOSO");
}).fail((err) => {
console.log(err);
}).always(() => {
isSending = false;
});
}
};
let onMapError = function (error) {
isSending = false;
}
let getLocation = () => {
navigator.geolocation.getCurrentPosition(onMapSuccess, onMapError, {
enableHighAccuracy: true,
});
return getLocation;
}
document.addEventListener('deviceready', function (e) {
intervalId = setInterval(getLocation(), 30000);
cordova.plugins.backgroundMode.on('activate', function (e) {
cordova.plugins.backgroundMode.disableWebViewOptimizations();
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(getLocation(), 30000);
});
cordova.plugins.backgroundMode.on('deactivate', function (e) {
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(getLocation(), 30000);
});
});
#justin is wrong it works on Cordova 10+ but it does not support GPS however you can recall GPS function when you resume to app. I'm on Cordova 11.0.0 and its working fine. Also you can take a look a cordova-plugin-advanced-background-mode
cordova-plugin-background-mode does not work on Cordova 10. You can try downgrade to Cordova 9. The repo seems inactive for a while now, not sure if the author will ever fix it.

React-Native: read timestamp saved on Firebase, after updating it

I update a timestamp in a Firebase server every time I click a button on my react-native app (android).
The problem is that, after updating it, I want to read it and set my state with this timestamp.
Here is some code I found on the Internet, it updates the date on Firebase, reach the first 'then' block but then never go on, so never reach the second 'then' block and never show the alert(onlyDate);
I have no error about rules on Firebase, read and write are both available.
getDateServerFirebase = () => {
let fb_currentTime = firebase.database().ref('currentTime/');
fb_currentTime.update({ time: firebase.database.ServerValue.TIMESTAMP })
.then(() => {
fb_currentTime.once('value').then(function (data) {
//console.log(data);
let timestamp = data._value.time;
let fullDate = new Date(timestamp);
let onlyDate = fullDate.getDate() + '/' + (fullDate.getMonth()+1) + '/' + fullDate.getFullYear();
alert(onlyDate);
}, function serverTimeErr(err) {
console.log('Could not reach to the server time !');
});
}, function (err) {
console.log ('set time error:', err)
});
}
I tried this and still the same problem: writing works, reading not.
setData = () =>{
firebase.database().ref('prova/').set({
name:'luis',
surname:'rew'
}, function(error) {
if (error) {
// The write failed...
} else {
// Data saved successfully!
}
});
}
readData = () =>{
firebase.database().ref('prova/')
.once('value')
.then((data)=>{
alert(data);
})
}
Can someone help me??
The way you access response from firebase function is through running the val(); function on the result.
change this line
let timestamp = data._value.time;
into this:
let timestamp = data.val().time;

Background service mobilefirst 7.1 is not working

I downloaded the sample Location services project from https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/7.1/advanced-client-side-development/location-services-hybrid-applications/. From the sample I kept posChange trigger policy and i deleted the other two. And I am getting the location when app is opened. But not in the app is closed. Below the snippet
function getFirstPositionAndTrack() {
var geoPolicy = WL.Device.Geo.Profiles.RoughTracking();
geoPolicy.timeout = 60000;
geoPolicy.maximumAge = 10000;
geoPolicy.minChangeDistance = 3;
WL.Device.Geo.acquirePosition(
function(pos) {
var triggers = {
Geo: {
posChange: { // display all movement
type: "PositionChange",
minChangeDistance: 5,
callback: function(deviceContext) {
WL.Client.transmitEvent({ event: 'deviceLocation'}, true);
}
},
}
};
WL.Device.startAcquisition({ Geo: geoPolicy }, triggers, { Geo: alertOnGeoAcquisitionErr } );
},
function(geoErr) {
console.log(geoErr);
// try again:
getFirstPositionAndTrack();
},
geoPolicy
);
}
And in adapter to check background
WL.Server.setEventHandlers([
WL.Server.createEventHandler({ event: 'deviceLocation'}, deviceEvent)
]);
Procedure
function deviceEvent(event) {
WL.Logger.error(JSON.stringify(event));
}
And in onconnectSuccess I am calling the function and setting the keepAlive Property
getFirstPositionAndTrack()
WL.App.setKeepAliveInBackground(true);
And is there any other way to debug when app is in background or closed?

InAppBrowser not closing?

I'm using the InAppBrowser plugin (v1.1.1) with Cordova for an OAuth login process. Unfortunately, the InAppBrowser doesn't appear to be closing the browser. My "closeBrowser" function instead continually triggers the interval, and the browser remains on-screen on the Android (I have not tried other devices at this time.)
Is there a way to forcibly close the InAppBrowser other than .close(), or hide it? Or maybe there's a flaw in my code somewhere that is locking the browser.
LogInPage.prototype.handleExternalLogin = function (externalLogin) {
var _this = this;
var ref = window.open(Environment_1.settings.baseUrl + externalLogin.route.url, "_blank", "location=no");
ref.addEventListener('loadstart', function (event) {
if (_.startsWith(event.url, Environment_1.settings.baseUrl + "/api/Account/account/ExternalLoginCallback")) {
// Now we want to load a different url that will give us the mobile access token
console.log('get external-mobile-token');
_this.closeBrowser(ref);
var ref2 = window.open(Environment_1.settings.baseUrl + "/api/Account/external-mobile-token", "_blank" /*, "location=no"*/);
ref2.addEventListener('loadstop', function (event) {
console.log('loadstop ' + event.url);
if (event.url == Environment_1.settings.baseUrl + "/api/Account/external-mobile-token") {
ref2.executeScript({ code: 'window.document.documentElement.innerText' }, function (contents) {
_this.login(contents);
_this.closeBrowser(ref2);
});
}
});
ref2.addEventListener('loaderror', function (event) {
console.log(event);
_this.closeBrowser(ref2);
// TODO - do something?
});
}
});
ref.addEventListener('loaderror', function (event) {
console.log(event);
_this.closeBrowser(ref);
// TODO - do something?
});
};
LogInPage.prototype.closeBrowser = function (browser) {
var interval = setInterval(function () {
console.log('closing');
browser.close();
}, 10);
browser.addEventListener('exit', function () {
console.log('closed');
clearInterval(interval);
});
};
LogInPage.prototype.login = function (token) {
console.log(token);
};
The above code is actually generated from TypeScript, but I figured I wouldn't confuse the issue.
It appears that closing an InAppBrowser and opening another at the same time was causing the issue; rewriting the process to only need one window solved my issue.

Unable to call geolocationerror when gps is disabled

When gps is enabled geolocationsuccess work perfectly. But when gps diabled it not calling geolocationerror in mobile device.Working on ionic framework using phonegap geolocation for checking is gps enable or not. codes are here
var locOptions = {
maximumAge : 10000,
timeout : 5000,
enableHighAccuracy : true
};
function onLocationSuccess(position) {
console.log(position);
// alert('success');
$rootScope.pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': $rootScope.pos}, function address(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$rootScope.currentposition = results[1].formatted_address;
console.log($rootScope.currentposition);
if($scope.switchToState=='signedIn'){
$ionicLoading.hide();
$http.get($rootScope.url +'api/price/?key=movo1026868hk738hkl')
.success(function(response) {
$rootScope.truckfare=response.datasets;
});
console.log('reached here2');
$state.go('app.home');
}
else{
$ionicLoading.hide();
$state.go('start');
}
}
}
});
}
// onError Callback receives a PositionError object
//
function onLocationError(error) {
alert("Geolocation error: #" + e.code + "\n" + e.message);
}
navigator.geolocation.getCurrentPosition(onLocationSuccess, onLocationError, locOptions);
Geolocation API will not give you an error if the GPS is off because that is not an error state. It will just timeout if it is not able to get a lock in the time limit you specify.
Unfortunately, this is a real problem. If you turn off GPS and Geolocation API times out, you will not be able to make it work again unless you restart a whole application. So even if you turn GPS back online API will not work again unless an application is restarted.
There's a simple workaround here. Before you initialize Geolocation API check if GPS is online. You can do that using this PhoneGap/Cordova plugin:
https://github.com/mablack/cordova-diagnostic-plugin
Essentially, this plugin will solve your initial problem + problem I mentioned you before.

Categories

Resources