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 - 這是在前景和背景之間轉換時以及在處於非活動狀態期間發生的狀態,例如進入多任務處理視圖或來電時

 

運行效果

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM