Reputation: 33
I'm trying to trigger the Back button on Android to close the application, but it just doesn't work.
On JS part, I can see this BackHandler.exitApp()
being executed:
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);
};
On the android side, I can see this portion being executed:
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
But since there's always a mReactInstanceManager, super.onBackPressed();
never gets called (which is the one who closes the app).
What am I missing? How should/can I see if I'm
Upvotes: 1
Views: 583
Reputation: 1313
try this:
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;
}
};
Upvotes: 1