ionic 3 background geo location stops in background - background

I am using plugin
https://github.com/mauron85/cordova-plugin-background-geolocation
its working fine, when in foreground, but once it goes to background it stops working. Please let me know how i can handle this.
Code in my LocationProvider's constructor function
const config: BackgroundGeolocationConfig = {
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
debug: true, // enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false, // enable this to clear background location settings when the app terminates
};
this.backgroundGeolocation.configure(config)
.subscribe((location: BackgroundGeolocationResponse) => {
this.zone.run(() => {
console.log(location);
})
});
Function after constructor
startTracking(){
console.log("Starting Tracking");
// start recording location
this.backgroundGeolocation.start();
}
Calling this function from home.ts constructor
this.location.startTracking();

Related

Sharing state for background task in react native

I am writing an app with Expo that uses expo-location to track the location of a user in the background. I would like to use hooks (states, useEffect...) when my app is in the background. At the moment the background tracking code looks like that
export default function BackgroundLocationHook() {
[...]
const [position, setPosition] = useState(null);
const [newLocation, setNewLocation] = useState(null) ;
TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
if (error) {
console.error(error);
return;
}
if (data) {
// Extract location coordinates from data
const { locations } = data;
const location = locations[0];
if (location) {
console.log("Location in background", location.coords);
}
}
setPosition(location.coords);
});
[...]
return [position];
}
But it is a bit hacky as the geolocation_tracking task shares some states with the
I would also like to play some sounds when I am close to a some location even when my app is in the background. I plan to do it with useEffect like that:
useEffect(() => {
const requestPermissions = async () => {
if(shouldPlaySound(newLocation)){
playSound()
}
};
requestPermissions();
}, [newLocation]);
This works when my app is in the foreground but I heard that react hooks such as states, and useEffect do not work when the app is in the background. So my question is what is the alternative to make sure I still have a sound being played when my app is in the background and if it is possible to have hooks working even when the app is in the background.
I see you want to perform some task in the background when you pass a specific location,
With the expo location, we can achieve this implementation.
You can add fencing to your desired location and when the device will enter the fencing area or exits from the fencing area you will get an event to handle some tasks and you are also able to listen to the event in the background with the Expo Task manager.
You need to follow the steps to achieve this.
Define a task using Expo Task Manager outside the react life cycle,
and read the official documentation for API usage. Expo Task Manager
Take the necessary permissions to access the location in the background, and start geofencing with your component. Expo Location
Stop the fencing listener using stopGeofencingAsync from expo-location when it is not needed anymore.
Now you will get events every time you enter or exit from the specified location in startGeofencingAsync until you stop using the stopGeofencingAsync method.
Hope this will help you achieve your desired input.
to run a task in the background you can check any of these library.
react-native-background-actions
react-native-background-timer
this is some example code
import BackgroundTimer from 'react-native-background-timer';
// Start a timer that runs continuous after X milliseconds
const intervalId = BackgroundTimer.setInterval(() => {
// this will be executed every 200 ms
// even when app is the background
console.log('tic');
}, 200);
// Cancel the timer when you are done with it
BackgroundTimer.clearInterval(intervalId);
// Start a timer that runs once after X milliseconds
const timeoutId = BackgroundTimer.setTimeout(() => {
// this will be executed once after 10 seconds
// even when app is the background
console.log('tac');
}, 10000);
// Cancel the timeout if necessary
BackgroundTimer.clearTimeout(timeoutId);
this is another example of this code
import BackgroundService from 'react-native-background-actions';
const sleep = (time) => new Promise((resolve) => setTimeout(() => resolve(), time));
// You can do anything in your task such as network requests, timers and so on,
// as long as it doesn't touch UI. Once your task completes (i.e. the promise is resolved),
// React Native will go into "paused" mode (unless there are other tasks running,
// or there is a foreground app).
const veryIntensiveTask = async (taskDataArguments) => {
// Example of an infinite loop task
const { delay } = taskDataArguments;
await new Promise( async (resolve) => {
for (let i = 0; BackgroundService.isRunning(); i++) {
console.log(i);
await sleep(delay);
}
});
};
const options = {
taskName: 'Example',
taskTitle: 'ExampleTask title',
taskDesc: 'ExampleTask description',
taskIcon: {
name: 'ic_launcher',
type: 'mipmap',
},
color: '#ff00ff',
linkingURI: 'yourSchemeHere://chat/jane', // See Deep Linking for more info
parameters: {
delay: 1000,
},
};
await BackgroundService.start(veryIntensiveTask, options);
await BackgroundService.updateNotification({taskDesc: 'New ExampleTask description'}); // Only Android, iOS will ignore this call
// iOS will also run everything here in the background until .stop() is called
await BackgroundService.stop();
A third solution for android is the headlessjs that only works on android
you can tak help from this

Add express server and dockerize app built with vue-electron-builder

I built an electron vue app, When started the project I used Vue CLI Plugin Electron Builder
I`ve been asked to add an express REST server for all the main business logic functionality.
The express app should be stand-alone app running on docker container.
What I did until now is add the basic express server just for POC, I changed my backgraound.ts like this:
Before:
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 1200,
height: 800,
useContentSize: true,
frame: false,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env
.ELECTRON_NODE_INTEGRATION as unknown as boolean,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
preload: path.join(__dirname, "preload.js"),
enableRemoteModule: true,
},
});
win.maximize();
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string);
if (!process.env.IS_TEST) win.webContents.openDevTools();
} else {
createProtocol("app");
// Load the index.html when not in development
win.loadURL("app://./index.html");
}
}
After:
...
import "./express-app/index.ts";
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 1200,
height: 800,
useContentSize: true,
frame: false,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env
.ELECTRON_NODE_INTEGRATION as unknown as boolean,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
preload: path.join(__dirname, "preload.js"),
enableRemoteModule: true,
enableBlinkFeatures: "Serial",
},
});
win.maximize();
win.hide();
win.loadURL("http://localhost:3000/");
// if (process.env.WEBPACK_DEV_SERVER_URL) {
// // Load the url of the dev server if in development mode
// await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string);
// if (!process.env.IS_TEST) win.webContents.openDevTools();
// } else {
// createProtocol("app");
// // Load the index.html when not in development
// win.loadURL("app://./index.html");
// }
}
My express index.ts
import express from "express";
const app = express();
app.get("/", () => {
console.log("Get Request");
});
app.listen(3000, () => {
// tslint:disable-next-line:no-console
console.log(`server started at http://localhost:${3000}`);
});
So I just changed the part of win.loadURL() in the createWindow() boilerplate of the cli-plugin
I wanted to know how to add a dockerfile suitable for my scenario

ionic vue background geolocation tracking stops after 5 minute

I am using plugin
https://github.com/seididieci/capacitor-backround-geolocation
to watch the user's location. then I am tracking that location with the help of a pusher. this background location works only for 5 minutes after that it just stops. I am using Capacitor's Background task. But that plugin also keeps data on phone after the user opens the app. the Background task sends data to the pusher.
Here is watch location function
getLocation: async function () {
BackgroundGeolocation.initialize({
notificationText: "Your app is running, tap to open.",
notificationTitle: "App Running",
updateInterval: 10000,
requestedAccuracy: BgGeolocationAccuracy.HIGH_ACCURACY,
// Small icon has to be in 'drawable' resources of your app
// if you does not provide one (or it is not found) a fallback icon will be used.
smallIcon: "ic_small_icon",
// Start getting location updates right away. You can set this to false or not set at all (se below).
startImmediately: true,
});
// const geolocation = new Geolocation.Geolocation();
BackgroundGeolocation.addListener("onLocation", (location) => {
// console.log("Got new location", location);
this.subscribe(location.longitude, location.latitude);
console.log(location)
});
BackgroundGeolocation.addListener("onPermissions", (location) => {
// console.log("BGLocation permissions:", location);
this.subscribe(location.longitude, location.latitude);
// Do something with data
});
BackgroundGeolocation.start();
},
Then calling function in mounted()
mounted(){
this.getLocation
App.addListener("appStateChange", (state) => {
setInterval(this.getLocation, 120000);
if (!state.isActive) {
BackgroundTask.beforeExit(async () => {
setInterval(this.getLocation, 120000);
console.og('Why')
});
}
if (state.isActive) {
setInterval(this.getLocation, 120000);
console.log('Active')
}
});
}
You need to use https://ionicframework.com/docs/native/foreground-service like this for running the background.

How to create BrowserWindow with data, and get that data in vue app?

I have a Electron-Vue project, and in this project i want to pass data to window when I want to show or create it, then get that data and pass to VUE application, to specify state for application.
And the data which i want to pass is a string to specify application state something like :
download or main or etc
then with above strings I'll set state in my application to render layouts base on specific state on creating window. basically i want to pass main for win and download for downloadWin
Here's background.js which i want to pass my data in new BrowserWindow(), i don't want to use ipcRendeder or ipcMain.
let win
let downloadWin
function createDownloadWindow() {
// Create the browser window.
downloadWin = new BrowserWindow({ // if it's win i wanna pass main if it's downloadWin i wanna pass download
title: 'Manage Downloads',
width: 1200,
height: 700,
minWidth: 1200,
minHeight: 700,
frame: false,
titleBarStyle: 'hiddenInset',
webPreferences: {
webSecurity: false,
devTools: true,
nodeIntegration: false,
nodeIntegrationInWorker: false,
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js"), /* eng-disable PRELOAD_JS_CHECK */
}
})
}
Now i want to get above string from creating window in main.js to pass received data from mainProcess to vue app.
new Vue({
router,
store,
vuetify,
mounted() {
this.$store.dispatch('window/setWindowStat', '//SET STRING HERE')
},
render: h => h(App)
}).$mount('#app')
You can pass any data you want via IPC:
in the Main process: https://www.electronjs.org/docs/api/ipc-main
in the Renderer process: https://www.electronjs.org/docs/api/ipc-renderer
Here is an example:
// In main process.
const { ipcMain } = require('electron')
ipcMain.on('hey', (event, arg) => {
console.log('hey from win', arg) // prints "{a: 2}" in main process console
})
// send message to your window when it ready (win is your window)
win.webContents.send('hi', {data: 'is here'})
import { ipcRenderer } from 'electron'
ipcRenderer.on('hi', (e, payload) => {
console.log('hi from main', payload) // prints: {data: 'is here'} in dev tools
})
ipcRenderer.send('hey', 'ping', {a: 2})

How to set interval in background GPS tracking?

I am using "react-native-background-geolocation" for user location tracking when the app is in the background.
Then is it possible to set interval in this function when device powered-up again? (on boot)
I want to get the user location constantly in the background once user turn on device.
How to set "setInterval" on this?
That is my code.
componentWillMount = async () => {
// This handler fires whenever bgGeo receives a location update.
BackgroundGeolocation.onLocation(this.onLocation, this.onError);
// This handler fires when movement states changes (stationary->moving; moving->stationary)
BackgroundGeolocation.onMotionChange(this.onMotionChange);
// This event fires when a change in motion activity is detected
BackgroundGeolocation.onActivityChange(this.onActivityChange);
// This event fires when the user toggles location-services authorization
BackgroundGeolocation.onProviderChange(this.onProviderChange);
////
// 2. Execute #ready method (required)
//
BackgroundGeolocation.ready(
{
// Geolocation Config
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 10,
// Activity Recognition
stopTimeout: 1,
// Application config
debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
stopOnTerminate: false, // <-- Allow the background-service to continue tracking when user closes the app.
startOnBoot: true, // <-- Auto start tracking when device is powered-up.
// HTTP / SQLite config
url: 'http://yourserver.com/locations',
batchSync: false, // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
autoSync: true, // <-- [Default: true] Set true to sync each location to server as it arrives.
headers: {
// <-- Optional HTTP headers
'X-FOO': 'bar',
},
params: {
// <-- Optional HTTP params
auth_token: 'maybe_your_server_authenticates_via_token_YES?',
},
},
(state) => {
console.log(
'- BackgroundGeolocation is configured and ready: ',
state.enabled,
);
if (!state.enabled) {
////
// 3. Start tracking!
//
BackgroundGeolocation.start(function () {
console.log('- Start success');
});
}
},
);
};