pomo
pomo

Reputation: 2301

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.

Upvotes: 5

Views: 5706

Answers (2)

Pratap Sharma
Pratap Sharma

Reputation: 2743

Though I may be very late in giving the answer it may help other facing the issue.

Recently I came across the same requirement where I have to move the app to the background. I tried the solution provided by @pomo. Though it worked I faced problems. Sometimes on multiple clicking of the back button, the app misbehaves in android though it worked perfectly fine in iOS.

And then I came across the following issues in GitHub where it mentions the reason for the misbehaviour.

The following solution works perfectly fine now.

// android/app/.../MainActivity.java
@Override
public void invokeDefaultOnBackPressed() {
    moveTaskToBack(true);
}
<!-- AndroidManifest.xml -->
<activity
    ...
    android:launchMode="singleTop">

Link from where I get the solution

I hope I'm able to help guys with the same requirement.

Upvotes: 6

pomo
pomo

Reputation: 2301

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

Upvotes: 11

Related Questions