公司app开发,react-native(android)要实现点击手机物理键back返回和退出app功能,本人也是小白,不是很懂,但是作为一个app,这是基本功能,所以必须实现。下面两个方案的coding中有什么写的不好的地方请多多包涵,亲测没问题,两个方法都跑的通,开始代码......
import { ToastAndroid,
AppState,
BackHandler,
Platform,StyleSheet,View,Text,ScrollView,AsyncStorage } from 'react-native';
方法一:
将代码写到app.js主入口文件中
const firstClick = 0;(定义一个常量,写在哪里都懂)
constructor(props) {
super(props);
this.state = {
selectedTab: 'home',
}
this.handleBack = this.handleBack.bind(this);
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBack)
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBack)
}
handleBack = () => {
var timestamp = (new Date()).valueOf();
if (timestamp - firstClick > 1000) {
firstClick = timestamp;
return false;
} else {
ToastAndroid.show('退出程序', ToastAndroid.SHORT);
BackHandler.exitApp();
return true;
}
}
方法二:这个方法借鉴网上的coding并且个人做了修改,原方法并不能退出,我是结合了当前router所在位置做判断,我用的是react-native-router-flux中的scence,并且限制Actions.state.index来实现页面的首页双击退出其他页面back正常返回。
将代码写到app.js主入口文件中
// constructor(props){
// super(props);
// this.state = {
// test: "wbd",
// };
// }
// 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() {
// lastBackPressed = Date.now();
// if (Actions.state.index == 0) {
// if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
// BackHandler.exitApp();
// }
// ToastAndroid.show('退出应用', ToastAndroid.SHORT);
// return true;
// };
// }
// _onAppStateChanged() {
// switch (AppState.currentState) {
// case "active":
// console.log("active");
// break;
// case "background":
// console.log("background");
// break;
// default:
// }
// }
ok,两个简单的实现方法都写了,可以考虑试试好不好用...