如何从React-Native获取onresume事件? 我想在Android主要活动恢复时进行一些检查。 我检查了RN的源代码,但是当应用程序恢复时似乎没有事件。
答案 0 :(得分:3)
您可以使用 AppState
阅读本文件
https://facebook.github.io/react-native/docs/appstate.html
答案 1 :(得分:2)
This method is called every-time when user come back again this screen.
This method is same as in android onResume() method – Keshav Gera 6 mins ago Delete
render(){
this.props.navigation.addListener(
'didFocus',
payload => {
console.log("Payload is called .....................")
}
);
}
答案 2 :(得分: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!')
}
this.setState({appState: nextAppState});
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
);
}
}
来源:https://facebook.github.io/react-native/docs/appstate.html
答案 3 :(得分:0)
command: python code.py
答案 4 :(得分:-1)
我最终为此推出了自己的解决方案。实现起来非常简单。
确保所有活动都扩展同一类,并在其中进行以下操作:
import com.facebook.react.bridge.Arguments
import com.facebook.react.modules.core.DeviceEventManagerModule
override fun onResume() {
super.onResume()
val params = Arguments.createMap()
params.putInt("rootViewTag", reactRootView!!.rootViewTag)
val reactContext = reactRootView!!.reactInstanceManager!!.currentReactContext!!
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java).emit("androidActivityResumed", params)
}
然后,在React方面执行以下操作:
import {DeviceEventEmitter} from 'react-native'
class MyComp extends React.Component {
componentDidMount() {
DeviceEventEmitter.addListener('androidActivityResumed', this._onAndroidActivityResumed)
}
componentWillUnmount() {
DeviceEventEmitter.removeListener('androidActivityResumed', this._onAndroidActivityResumed)
}
_onAndroidActivityResumed = (e) => {
if (e.rootViewTag === this.props.rootTag) {
// Do whatever you want here
}
}
}