background a react-native android app using back b

2019-01-15 11:35发布

问题:

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.

回答1:

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);
    }
}