In my app the user via a button can start a special mode where various GPS, BLE etc services are activated. Among these, I need the server to know in real time which users have this mode enabled. I figured the only way is to establish a socket.io connection. However on Android after a couple of minutes the connection is interrupted. Tried following what recommended an answer to a similar question but still nothing.
import React, {useEffect, useRef} from 'react';
import {AppState} from 'react-native'
export default () => {
const appState = useRef(AppState.currentState);
var interval
const _handleAppStateChange = (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
//clearInterval when your app has come back to the foreground
BackgroundTimer.clearInterval(interval)
}else{
//app goes to background
console.log('app goes to background')
//tell the server that your app is still online when your app detect that it goes to background
interval = BackgroundTimer.setInterval(()=>{
console.log('connection status ', socket.connected)
socket.emit('online')
},5000)
appState.current = nextAppState;
console.log("AppState", appState.current);
}
useEffect (() => {
AppState.addEventListener("change", _handleAppStateChange);
return () => {
AppState.removeEventListener("change", _handleAppStateChange);
};
},[])
}
The error I receive is "transport error". Thanks.
Activities in the background are killed for resources on Android after very brief amounts of time. You need to use a foreground Service (which can still be killed, but is less likely to be)but even that won't work forever. Android is not meant to have reliable background execution for power saving purposes. Even if you did use a foreground service your app will be under Doze mode restrictions once the screen is off (allowed only a brief window to do computation every 15 minutes, except for high priority push notifications. And those are limited as well to only so many per hour).