首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当应用程序在后台或在react原生中被杀死时,是否可以检查用户的移动活动?

当应用程序在后台或在react原生中被杀死时,是否可以检查用户的移动活动?
EN

Stack Overflow用户
提问于 2018-05-07 14:39:06
回答 1查看 869关注 0票数 1

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

在react-native中有没有可能让我们跟踪用户的移动活动(在后台和终止状态下),并跟踪位置或运行后台作业?

EN

回答 1

Stack Overflow用户

发布于 2018-05-27 23:58:17

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

代码语言:javascript
运行
复制
import { AppState } from 'react-native';
import BackgroundTimer from 'react-native-background-timer';


state = {
        appState: AppState.currentState
    }

在componentDidMount中使用以下命令:

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

在componentWillUnmount中:

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

使用像这样的函数,当应用程序在后台时,你会得到你的结果。

代码语言:javascript
运行
复制
_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 });
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50208376

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档