BackHandler不会关闭React Native应用

时间:2019-02-25 13:59:56

标签: react-native react-native-android

我正在尝试触发Android上的“后退”按钮以关闭该应用程序,但它不起作用。 在JS部分,我可以看到此BackHandler.exitApp()正在执行:

const handleHardwareBack = navigation => () => {
    // Back performs pop, unless we're to main screen [0,0]
    if (navigation.state.index === 0 || navigation.state.index === 2) {
        BackHandler.exitApp();
        return false;
    }
    return navigation.goBack(null);
};

在android方面,我可以看到这部分正在执行:

@Override
public void onBackPressed() {
    if (mReactInstanceManager != null) {
        mReactInstanceManager.onBackPressed();
    } else {
        super.onBackPressed();
    }
}

但是由于总是有一个mReactInstanceManager,因此super.onBackPressed();不会被调用(这是关闭应用程序的人)。

我想念什么?

1 个答案:

答案 0 :(得分:1)

尝试一下:

 import {BackHandler} from 'react-native';

export default class RoomType extends Component {
     _didFocusSubscription;
     _willBlurSubscription;
     constructor(props) {
         super(props);
         this._didFocusSubscription = props.navigation.addListener('didFocus',payload =>
            BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
         ); 
     }
  }
componentDidMount() {
        this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload =>
            BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
        );
 }
componentWillUnmount() {
        this._didFocusSubscription && this._didFocusSubscription.remove();
        this._willBlurSubscription && this._willBlurSubscription.remove();
    }
onBackButtonPressAndroid = () => {
    //code when you press the back button
    // Back performs pop, unless we're to main screen [0,0]
    if (navigation.state.index === 0 || navigation.state.index === 2) {
        BackHandler.exitApp();
        return true;
    }
 };