reactNative 监听前台 ,后台触发方法

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从原生代码得到通知为止


应用:

  1. export default class HomePager extends Component {
  2. constructor(props) {
  3. super(props);
  4. //设置一个标记,表示从后台进入前台的时候,处理其他逻辑
  5. this.flage = false
  6. }
  7. componentDidMount(){
  8. AppState.addEventListener('change',this._handleAppStateChange);
  9. }
  10. _handleAppStateChange = (nextAppState)=>{
  11. if (nextAppState!= null && nextAppState === 'active') {
  12. //如果是true ,表示从后台进入了前台 ,请求数据,刷新页面。或者做其他的逻辑
  13. if (this.flage) {
  14. //这里的逻辑表示 ,第一次进入前台的时候 ,不会进入这个判断语句中。
  15. // 因为初始化的时候是false ,当进入后台的时候 ,flag才是true ,
  16. // 当第二次进入前台的时候 ,这里就是true ,就走进来了。
  17. //测试通过
  18. // alert("从后台进入前台");
  19. // 这个地方进行网络请求等其他逻辑。
  20. }
  21. this.flage = false ;
  22. }else if(nextAppState != null && nextAppState === 'background'){
  23. this.flage = true;
  24. }
  25. }
  26. componentWillUnmount() {
  27. AppState.removeEventListener('change', this._handleAppStateChange);
  28. }
  29. }
完美测试!!!!!!!!!

猜你喜欢

转载自blog.csdn.net/xtyzmnchen/article/details/80911883