react native 中提供了一个 AppStates 这样一个api 给我们使用 。
官方解释:
AppState能告诉你应用当前是在前台还是在后台,并且能在状态变化的时候通知你。
AppState通常在处理推送通知的时候用来决定内容和对应的行为
状态:
active - 应用正在前台运行
background - 应用正在后台运行。用户既可能在别的应用中,也可能在桌面。
inactive - 这是一个过渡状态,不会在正常的React Native应用中出现
方法 :
static addEventListener(type: string, handler: Function)
添加一个监听函数,用于监听应用状态的变化。type参数应填change 。
static removeEventListener(type: string, handler: Function)
移除一个监听函数。type参数应填change。
注意:
要获取当前的状态,你可以使用AppState.currentState,这个变量会一直保持更新。不过在启动的过程中,currentState可能为null,直到AppState从原生代码得到通知为止
应用:
- export default class HomePager extends Component {
- constructor(props) {
- super(props);
- //设置一个标记,表示从后台进入前台的时候,处理其他逻辑
- this.flage = false
- }
- componentDidMount(){
- AppState.addEventListener('change',this._handleAppStateChange);
- }
- _handleAppStateChange = (nextAppState)=>{
- if (nextAppState!= null && nextAppState === 'active') {
- //如果是true ,表示从后台进入了前台 ,请求数据,刷新页面。或者做其他的逻辑
- if (this.flage) {
- //这里的逻辑表示 ,第一次进入前台的时候 ,不会进入这个判断语句中。
- // 因为初始化的时候是false ,当进入后台的时候 ,flag才是true ,
- // 当第二次进入前台的时候 ,这里就是true ,就走进来了。
- //测试通过
- // alert("从后台进入前台");
- // 这个地方进行网络请求等其他逻辑。
- }
- this.flage = false ;
- }else if(nextAppState != null && nextAppState === 'background'){
- this.flage = true;
- }
- }
- componentWillUnmount() {
- AppState.removeEventListener('change', this._handleAppStateChange);
- }
- }