BackHandler

参考文档

监听设备上的后退按钮事件。

Android:监听后退按钮事件。如果没有添加任何监听函数,或者所有的监听函数都返回 false,则会执行默认行为,退出应用。

tvOS(即 Apple TV 机顶盒):监听遥控器上的后退按钮事件(阻止应用退出的功能尚未实现)。

iOS:尚无作用。

监听函数是按倒序的顺序执行(即后添加的函数先执行)。如果某一个函数返回 true,则后续的函数都不会被调用。

方法

exitApp()

static exitApp()

addEventListener()

static addEventListener(eventName, handler)

removeEventListener()

static removeEventListener(eventName, handler)

Example

示例

import React, { Component } from 'react';
import {View,StyleSheet,BackHandler ,Dimensions,ToastAndroid} from 'react-native';
const {height,width}=Dimensions.get('window');
export class pageComponent extends Component {
    constructor(props){
        super(props);
    }
    componentDidMount() {
        BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
    }
    componentWillUnmount() {
        BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
    }
    //安卓返回键关闭APP
    onBackPress = () => {
        if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
            //最近2秒内按过back键,可以退出应用。
            BackHandler.exitApp();
            NativeModules.EMPBridgeAddition.forceExit();
            return false;
        }
        this.lastBackPressed = Date.now();
        alert("再按一次将退出APP");
        return true
    };
    render(){
        return(
            <View style={styles.container}>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    container: {
        flex:1,
        alignItems: 'center',
        justifyContent:'center'
    },
    tabBarIOS:{
        height:40,
        width:width
    }
});
该文件修订时间: 2021-01-14 15:02:10

results matching ""

    No results matching ""