Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background a react-native android app using back button

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.

like image 280
pomo Avatar asked Sep 22 '16 09:09

pomo


People also ask

How do I control the Back button in React Native?

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.

How do you handle the back button in react navigation?

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.

Which callback of modal is fired when hardware back button is pressed?

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.

How do you stop Goback in React Native?

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} /> ).


1 Answers

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);
    }
}
like image 88
pomo Avatar answered Oct 13 '22 03:10

pomo