您的位置:首页 > 移动开发

React Native 监听Back双击退出实现+APP前后台状态监听

2018-01-16 14:14 519 查看
/**

* 关于前后台监听,HOME直接后台不执行component相关周期函数,back

* 后台是执行的,back后返回应该是重新render了,所以监听HOME或者

* BACK可以同一使用APPState的状态码来操作

* APPState是有三个状态码的,有一个不常用就没写

*/

import React, { Component } from 'react';
import {
ToastAndroid,
AppState,
BackHandler,
TouchableHighlight,
Platform,
StyleSheet,
Text,
View,
Alert
} from 'react-native';

const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});

const lastBackPressed = Date.now();

type State = {
test: string,
};

export default class App extends Component<Props,State>{

constructor(props: Props){
super(props);
this.state = {
test: "hello",
};
}

//组件加载之后添加监听
componentDidMount() {
if(Platform.OS === 'android') BackHandler.addEventListener('hardwareBackPress', this._onBackPressed);
AppState.addEventListener('change', this._onAppStateChanged);
}

//组件卸载之前移除监听
componentWillUnmount() {
if(Platform.OS === 'android') BackHandler.removeEventListener('hardwareBackPress', this._onBackPressed);
AppState.removeEventListener('change', this._onAppStateChanged);
}

_onBackPressed() {
if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
BackHandler.exitApp();
}
lastBackPressed = Date.now();
ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
return true;
}

_onAppStateChanged() {
switch (AppState.currentState) {
case "active":
console.log("active");
break;
case "background":
console.log("background");
break;
default:

}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
<TouchableHighlight onPress={
()=> {
this.setState({test: "aaaa"});
}
}>
<Text>{this.state.test}</Text>
</TouchableHighlight>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: