React Native如何检测屏幕解锁?

8

有没有办法检测用户何时打开了他们的手机?据我所知,当设备解锁(例如输入正确密码)时,android.intent.USER_PRESENT会广播,但是我不知道如何在React Native中检测广播。有人有解决方案吗?


2
我不知道是否已经建立了桥梁,但如果发出了事件,您可以监听它。 - Max Millington
1个回答

14

请查看 FB (Facebook) 的 AppState API

该 API 在 FB 上有3种状态,总共有5种。但在 FB 中只能看到3种状态,另外2种可能被支持也可能不被支持。

Active - 应用正在前台运行

background - 应用正在后台运行。用户可能在另一个应用中或在主屏幕上。

inactive - 当前应用处于前台和后台之间的状态,或者在进入多任务视图或接收来电时处于不活动状态。

查看苹果的 文档 了解更多信息。

你需要测试当手机处于锁屏状态时会触发哪个状态。我无法告诉你要使用哪个状态,因为我从未测试过此 API。

如下代码所示,测试是在条件语句中完成的。

 if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') 

我这里以Facebook为例,但是请将change事件监听器附加到componentDidMount中,并在ComponentWillUnmount中删除,这样代码将根据状态运行。

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接