在本机上每个用户级别的应用使用时间

时间:2019-11-20 05:49:07

标签: javascript react-native google-analytics

我正在开发一个本机应用程序,我想找到一种方法来获取基于用户的应用程序使用时间。

1 个答案:

答案 0 :(得分:1)

使用react native的 AppState 检查应用是否处于活动状态或处于后台。

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!. save this time');
    }
    console.log('App sent to the background!. save this time. ');
    /// difference between both the times is the time spent by user on app
    this.setState({appState: nextAppState});
  };

  render() {
    return <Text>Current state is: {this.state.appState}</Text>;
  }
}