zoukankan      html  css  js  c++  java
  • react native android 应用状态(前端或后台)的判断

    当Android应用程序被暂时放到了后台,或者又重新回到前台,是否有相应的事件可以处理到?

    例如,当你的应用暂时放到了后台,是否应该做出一些操作,暂时保存界面上的数据?

    可以参考:https://github.com/wix/react-native-navigation/issues/839

    官方文档:https://facebook.github.io/react-native/docs/appstate.html

    官方示例代码:

    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>
        );
      }
    
    }

    做法是:引用AppState

    import { AppState } from 'react-native';

    在组件的componentDidMount事件中,增加以下代码

        componentDidMount() {
            console.log('componentDidMount================');
            AppState.addEventListener('change', (state) => {
                if (state === 'active') {
                    console.log('state active');
                } else if (state === 'background') {
                    console.log('background');
                } else if (state === 'inactive') {
                    console.log('inactive');
                }
            });
        }

    App States
    active - 该应用程序在前台运行
    background - 该应用程序正在后台运行。用户是:
    在另一个应用中
    在主屏幕上
    [Android]在另一个Activity(即使它是由您的应用程序启动)
    inactive - 这是在前景和背景之间转换时以及在处于非活动状态期间发生的状态,例如进入多任务处理视图或来电时

    运行效果

  • 相关阅读:
    二分查找 【数组的二分查找】
    二分答案 [TJOI2007]路标设置
    队测 逆序对 permut
    【线段树】 求和
    状压DP Sgu223 骑士
    状压DP Poj3311 Hie with the Pie
    状压DP入门 传球游戏之最小总代价
    状压DP 小W选书籍
    状压DP [Usaco2008 Nov]mixup2 混乱的奶牛
    __gcd()用法
  • 原文地址:https://www.cnblogs.com/weschen/p/9055799.html
Copyright © 2011-2022 走看看