I've followed the example pattern for handling the android back button in the react-native docs and it works well. I can use the hardware back button to pop my navigation stack.
At the point that there's only 1 view in the stack though I don't pop it (just like the example), and I return false from my hardwareBackPress
event listener. At this point it I see the componentWillUnmount
method being called in my final view, at which point my app shuts down.
If I return true then nothing happens at all obviously.
What I want to happen is that the app merely gets "backgrounded" instead of exiting completely.
To handle the Android Back Button Press in the React Native we have to register the hardwareBackPress event listener with a callback function, which will be called after pressing the Back Button.
By default React Navigation will handle the Android back button for you, however we'll need to override the defaults. If you're at the top of the stack and press the android back button the application will close. If you've navigated within the stack anywhere then the screen will pop.
The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds. It is Android-only.
To make this work, you need to: Disable the swipe gesture for the screen ( gestureEnabled: false ). Override the native back button in the header with a custom back button ( headerLeft: (props) => <CustomBackButton {... props} /> ).
Answered my own question. The trick is to override the default back button behaviour in the MainActiviy
:
public class MainActivity extends ReactActivity {
@Override
protected String getMainComponentName() {
return "foo";
}
@Override
public void invokeDefaultOnBackPressed() {
// do not call super. invokeDefaultOnBackPressed() as it will close the app. Instead lets just put it in the background.
moveTaskToBack(true);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With