With @react-native-community/hooks you can use the useAppState hook to check the app state. When you close the app, it gets a state of unknown once you open it back. When is in background, it says background' or 'inactive'.
Currently, there is, unfortunately, no support for background tasks of any kind. The feature you are referring to would be a background timer. Such a timer is this product pain (a feature request) for react native, you may upvote it to show an increased demand for this feature.
Looks like you can detect the previous state and compare it to the next state. You can't detect that the app is closing vs going into the background, from what I can find online, but you can detect if it was inactive
(closed), or in the background
.
import React, {Component} from 'react'
import {AppState, Text} from 'react-native'
class AppStateExample extends Component {
state = {
appState: AppState.currentState
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({appState: nextAppState});
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
);
}
}
I suggest to use web socket and it will help you to solve your problem, as following :
react native app
import React from 'react';
const io = require('socket.io-client/dist/socket.io');
const App = ()=>{
React.useEffect(()=>{
// connect to web socket
window.appSocket = io.connect(`<server-origin>/?token=<string>&userAppId=<string>`);
window.appSocket.on('connect',()=>{
// do what you line
})
},[])
...
}
export default App;
express server side
const express = require('express');
const server = express();
const http = require('http').Server(server);
const io = require('socket.io')(http);
io.on('connection',(socket)=>{ // this callback function for each web socket connection
let { token , userAppId } = socket.handshake.query;
if( userAppId ){
console.log(`${userAppId} online`)
socket.on('disconnect',(resean)=>{
console.log(`${userAppId} shut down`)
})
}
});
for more details, you can check socket.io
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With