问题描述
当我的本机应用程序转到后台或前台时,我遇到问题.当应用在后台或前台但无法找到任何解决方案时,我试图在设定的时间间隔内调用操作.
I have a problem when react native app goes to background or foreground. I am trying to call my action in a set interval when app in background or foreground but unable to find any solution.
在我的应用程序中,当用户单击开始导航"按钮并将其重定向到手机的默认地图"应用程序时.当应用未激活时,我需要在一定时间间隔内更新数据库.
In my app when user click on start navigation button and it redirect user to the Default map application of phone. I need to update my Database in a time interval when app not active.
我已使用Appstate来检查应用程序何时未激活.并将setInterval函数设置为在一组时间间隔内调用操作.
I have used Appstate to check when app is not active. And set setInterval function to call action in a set of time interval.
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._interval = setInterval( () => {
console.log('check');
}, 5000);
if(global.routeName && global.routeName != '' && global.routeName == "OrderDetail"){
this.props.navigation.navigate("OrderDetail",{orderId: global.orderId});
}
}else{
this._interval = setInterval( () => {
console.log('check 2');
}, 5000);
}
this.setState({appState: nextAppState});
};
我希望当应用程序进入后台或前台时,setInterval应该在一组间隔中调用,但实际上我无法获取我的输出.
I expected when app goes to background or foreground setInterval should be call in a set of interval, but the actual i'm unable to get my output.
推荐答案
当应用程序在后台运行时,"setInterval"将无法运行.您可以使用 react-native-background-timer
示例代码
BackgroundTimer.runBackgroundTimer(() => {
//code that will be called every 3 seconds
},
3000);
//rest of code will be performing for iOS on background too
BackgroundTimer.stopBackgroundTimer(); //after this call all code on background stop run.
这篇关于当应用程序在本机中处于前台或后台时如何调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!