diff --git a/App.tsx b/App.tsx index 7c5db10b0..85d6aaf2f 100644 --- a/App.tsx +++ b/App.tsx @@ -143,8 +143,31 @@ import CustodialWalletWarning from './views/Settings/CustodialWalletWarning'; import PSBT from './views/PSBT'; import TxHex from './views/TxHex'; +import { BackHandler, NativeEventSubscription } from 'react-native'; export default class App extends React.PureComponent { + private backPressListenerSubscription: NativeEventSubscription; + + private handleBackPress = (navigation: any) => { + const dialogHasBeenClosed = Stores.modalStore.closeVisibleModalDialog(); + if (dialogHasBeenClosed) { + return true; + } + + if (Stores.settingsStore.loginRequired()) { + BackHandler.exitApp(); + return true; + } + + const navigationState = navigation.getState(); + if (navigationState.routes.length > 1) { + navigation.pop(); + return true; + } + + return false; + }; + render() { const Stack = createStackNavigator(); return ( @@ -190,6 +213,21 @@ export default class App extends React.PureComponent { headerShown: false, animationEnabled: false }} + screenListeners={({ navigation }) => ({ + focus: () => { + this.backPressListenerSubscription?.remove(); + this.backPressListenerSubscription = + BackHandler.addEventListener( + 'hardwareBackPress', + () => + this.handleBackPress( + navigation + ) + ); + }, + blur: () => + this.backPressListenerSubscription?.remove() + })} > { } private handleBackButton() { - const dialogHasBeenClosed = - this.props.ModalStore.closeVisibleModalDialog(); - if (dialogHasBeenClosed) { - return true; - } - - const navigation = this.props.navigation; - - if (this.props.SettingsStore.loginRequired()) { - // popToTop to close all screens and return false to close the app - navigation.popToTop(); - return false; - } - - const navigationState = navigation.getState(); - if (navigationState.routes.length > 1) { - navigation.pop(); - return true; - } - const tabNavigator = this.tabNavigationRef.current; if (!tabNavigator) { return false; @@ -197,20 +177,26 @@ export default class Wallet extends React.Component { return false; } - handleFocus = () => this.getSettingsAndNavigate(); + private handleFocus = () => { + this.backPressSubscription?.remove(); + this.backPressSubscription = BackHandler.addEventListener( + 'hardwareBackPress', + this.handleBackButton.bind(this) + ); + this.getSettingsAndNavigate(); + }; + + private handleBlur = () => this.backPressSubscription?.remove(); async componentDidMount() { // triggers when loaded from navigation or back action this.props.navigation.addListener('focus', this.handleFocus); + this.props.navigation.addListener('blur', this.handleBlur); this.handleAppStateChangeSubscription = AppState.addEventListener( 'change', this.handleAppStateChange ); - this.backPressSubscription = BackHandler.addEventListener( - 'hardwareBackPress', - this.handleBackButton.bind(this) - ); } componentWillUnmount() {