我们正在开发实时位置共享应用程序,当应用程序在后台运行时,我们必须运行我们的作业,如果它在移动,我们需要获得用户的位置。
在react-native中有没有可能让我们跟踪用户的移动活动(在后台和终止状态下),并跟踪位置或运行后台作业?
发布于 2018-05-27 23:58:17
试着倾听AppState的变化,当你的应用程序进入后台时,你应该开始做你想做的事情。
import { AppState } from 'react-native';
import BackgroundTimer from 'react-native-background-timer';
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!');
} else {
console.log('App is in background');
const interval = BackgroundTimer.setInterval(() => {
console.log('listen for location changes here');
if (this.state.appState === 'active') {
//Stop the interval when AppState goes
//back to active again
BackgroundTimer.clearInterval(interval);
}
}, 1000);
}
}
this.setState({ appState: nextAppState });
}https://stackoverflow.com/questions/50208376
复制相似问题