【问题标题】:Is it possible to check user's moving activity when app is in background or killed in react native?当应用程序在后台或在本机反应中被杀死时,是否可以检查用户的移动活动?
【发布时间】:2018-05-07 06:39:05
【问题描述】:

我们正在开发实时位置共享应用程序,我们必须在应用程序处于后台时运行我们的工作,如果它正在移动,我们需要获取用户的位置。

在 react-native 中是否有任何可能性,以便我们可以跟踪用户移动活动(在后台和终止状态)并跟踪位置或运行后台作业?

【问题讨论】:

  • 我建议react-native-mauron85-background-geolocation 可以在应用程序在前台或后台运行时保留用户的位置。
  • 是的,我们使用了它,但问题是当应用程序被杀死或在后台我们没有 api 将位置发送到服务器时,我们的 react native js 代码没有运行(我们使用 firebase 作为后端),并且该库由于设备保持清醒而消耗更多电池

标签: react-native location accelerometer sensors


【解决方案1】:

尝试监听 AppState 的变化,当你的应用进入后台时,你应该开始做你想做的事情。

import { AppState } from 'react-native';
import BackgroundTimer from 'react-native-background-timer';


state = {
        appState: AppState.currentState
    }

在 componentDidMount 中使用这个:

AppState.addEventListener('change', this._handleAppStateChange);

在组件WillUnmount 中:

AppState.removeEventListener('change', this._handleAppStateChange);

使用类似这个函数,当应用在后台时,你会得到你的结果。

_handleAppStateChange = (nextAppState) => {
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
            console.log('App has come to the foreground!');
        } else {
            console.log('App is in background');
            const interval = BackgroundTimer.setInterval(() => {
                    console.log('listen for location changes here');
                    if (this.state.appState === 'active') {
                        //Stop the interval when AppState goes 
                        //back to active again
                        BackgroundTimer.clearInterval(interval);
                    }
                }, 1000);
          }
        }
        this.setState({ appState: nextAppState });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多