react-navigation icon indicating copy to clipboard operation
react-navigation copied to clipboard

Android Hardware Back Button not Working

Open StevePotter opened this issue 9 years ago • 32 comments

Great work on this package. Pressing the back button in the nav header works, but if I press the back button on the device, nothing happens.

I looked in the source and found 'backPress' handled from BackAndroid: https://github.com/react-community/react-navigation/blob/master/src/createNavigationContainer.js#L157

There are two problems here. First, the hardwareBackPress needs to be handled and it should return true/false to prevent the app from exiting if indeed the user can navigate backwards.

For now I've written this functionality into my app but since some work has been put in to handle Android, I would expect it to work for the phone's physical back button. I'd be happy to submit a PR if it will be taken seriously.

Thanks for your work and let me know if I can help.

StevePotter avatar May 19 '17 14:05 StevePotter

What is your RN version? We need a little more info for help you

rigobcastro avatar May 19 '17 17:05 rigobcastro

same problem, my RN version is 0.44.0

luhui avatar May 22 '17 08:05 luhui

@luhui check this https://github.com/react-community/react-navigation/issues/1330 could help

rigobcastro avatar May 22 '17 15:05 rigobcastro

Any workaround.? I've been struggling to handle android hardware back button.

Suresh-R-S avatar Jun 10 '17 10:06 Suresh-R-S

@Suresh-R-S Have you read this https://facebook.github.io/react-native/docs/backandroid.html? Maybe this is your problem

rigobcastro avatar Jun 10 '17 15:06 rigobcastro

@rigobcastro Yes i'am using backHandler, since backAndroid is deprecated from RN 0.44.0. I've added event listeners to all the screens. But I'am having trouble with removing the listener. The componentWillUnmount is not fired. Eg. If i have 2 screens, Scr 1 & Scr 2. Since the Scr 1 listener is not removed, pressing on hardware button from Scr 2 invokes the listener of Scr 1.

Suresh-R-S avatar Jun 10 '17 16:06 Suresh-R-S

@Suresh-R-S ok this is another problem, componentWillUnmount doesn't work and I don't know why (I have the same problem with tabs) but maybe componentDidMount works or try the use the listener in App.js I don't know, I think many listener for one event is not a good practice the good practice will be one listener and many callbacks in all components/screens/containers. It's my opinion.

rigobcastro avatar Jun 10 '17 17:06 rigobcastro

This is working in the most recent release! 😄

spencercarli avatar Aug 30 '17 02:08 spencercarli

@spencercarli which version ??

rahmatkruniawan avatar Sep 26 '17 06:09 rahmatkruniawan

What other packages are you using? In my case there was some weird conflict with react-native-video using react-windows. When I upgraded my react-native-video, BackHandler worked fine.

samdoj avatar Sep 29 '17 19:09 samdoj

@samdoj in dev mode work but on release mode back not working

rahmatkruniawan avatar Oct 02 '17 09:10 rahmatkruniawan

how to determine the hardware buttons in android devices are present or not in react native as there seem to be a lot of issues in styling various android devices please anyone could help me out in resolving that isuue

vikas199 avatar Nov 29 '17 01:11 vikas199

@rahmatkruniawan

I am on v0.46.0 of react-native and had the same issue. I tracked the issue down to this file in the react-native code base

https://github.com/facebook/react-native/blob/master/Libraries/Utilities/BackHandler.android.js#L25

When running with the chrome debugger turned off the line

var subscriptions = Array.from(_backPressSubscriptions.values()).reverse()

always returns an empty array for subscriptions which in turn causes the invokeDefault variable to stay true and the .exitApp() function to be called.

After more investigation, I think the issue was discovered and discussed in the following PR https://github.com/facebook/react-native/pull/15182.

Even after copy/pasting the PR change in an older version of RN it did not work most likely caused by the issue described in the PR.

After some very slight modifications I got it working by changing to

RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
  var invokeDefault = true;
  var subscriptions = []
  _backPressSubscriptions.forEach(sub => subscriptions.push(sub))

  for (var i = 0; i < subscriptions.reverse().length; ++i) {
    if (subscriptions[i]()) {
      invokeDefault = false;
      break;
    }
  }

  if (invokeDefault) {
    BackHandler.exitApp();
  }
});

Simply using a .forEach which was the original implementation on the PR before the amended Array.from syntax works throughout.

So you could fork react-native and use a modified version, submit a PR though I imagine that will take a little while to be approved and merged upstream, or you can do something similar to what I did which was to override the RCTDeviceEventEmitter.addListener(...) for the hardwareBackPress event.

// other imports
import { BackHandler, DeviceEventEmitter } from 'react-native'

class MyApp extends Component {
  constructor(props) {
    super(props)
    this.backPressSubscriptions = new Set()
  }

  componentDidMount = () => {
    DeviceEventEmitter.removeAllListeners('hardwareBackPress')
    DeviceEventEmitter.addListener('hardwareBackPress', () => {
      let invokeDefault = true
      const subscriptions = []

      this.backPressSubscriptions.forEach(sub => subscriptions.push(sub))

      for (let i = 0; i < subscriptions.reverse().length; i += 1) {
        if (subscriptions[i]()) {
          invokeDefault = false
          break
        }
      }

      if (invokeDefault) {
        BackHandler.exitApp()
      }
    })

    this.backPressSubscriptions.add(this.handleHardwareBack)
  }

  componentWillUnmount = () => {
    DeviceEventEmitter.removeAllListeners('hardwareBackPress')
    this.backPressSubscriptions.clear()
  }

  handleHardwareBack = () => { /* do your thing */ }
  
  render() { return <YourApp /> }
}

austenLacy avatar Jan 03 '18 16:01 austenLacy

@austenLacy I use this code ,still not work. 😂

haozes avatar Jan 04 '18 09:01 haozes

@haozes if you post the code that you have, I can try to help if you'd like

austenLacy avatar Jan 04 '18 14:01 austenLacy

@austenLacy I use this code, but it's still not working. I'm on

react-native: 0.52.0,
react-navigation: 1.0.0-beta.23

Here's some peace of my code in one js file:

class CustomDrawerView extends Component {
  constructor(props) {
    super(props);
    this.backPressSubscriptions = new Set();
  }

  componentDidMount = () => {
    DeviceEventEmitter.removeAllListeners('hardwareBackPress')
    DeviceEventEmitter.addListener('hardwareBackPress', () => {
      let invokeDefault = true;
      const subscriptions = [];

      this.backPressSubscriptions.forEach(sub => subscriptions.push(sub));

      for (let i = 0; i < subscriptions.reverse().length; i += 1) {
        if (subscriptions[i]()) {
          invokeDefault = false;
          break;
        }
      }

      if (invokeDefault) {
        BackHandler.exitApp();
      }
    });

    this.backPressSubscriptions.add(this.handleHardwareBack);
  }

  componentWillUnmount() {
    console.log('CustomDrawerView .. componentWillUnmount ..');
  //   if (Platform.OS === 'android') BackHandler.removeEventListener('hardwareBackPress');
    DeviceEventEmitter.removeAllListeners('hardwareBackPress');
    this.backPressSubscriptions.clear();
  }

  handleHardwareBack = () => {
    const { navigation } = this.props;
    if (navigation.state.routes.length === 1 &&
        (navigation.state.routes[0].routeName === 'StartUpScreen' ||
          navigation.state.routes[0].routeName === 'SignInScreen' ||
          navigation.state.routes[0].routeName === 'ListServicesScreen'
        )
      ) {
      return false;
    }

    navigation.dispatch(NavigationActions.back());
    return true;
  }

// some other logic for the Custom Drawer component
}

const CustomDrawer = createNavigationContainer(
  createNavigator(AppRouter)(CustomDrawerView)
);

class App extends Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    console.log('App .. componentWillMount ..');

    // configure firebase database
    firebase.initializeApp(firebaseConfig);
  }

  render() {
    const store = configureStore();

    store.dispatch(verifyIsLoggedIn());

    return (
      <Provider store={store}>
        <CustomDrawer />
      </Provider>
    );
  }
}

export default App;

I will be very happy if someone could help me with this BackButton on Android. I use console.log(...) in BackHandler listener but it's not fired and I don't know why. :( Thanks!

petarivanovv9 avatar Feb 01 '18 13:02 petarivanovv9

@pepincho is your CustomDrawerView component your root level app component? It needs to be in the root component because you don't want the app to unmount which would remove your custom listener.

austenLacy avatar Feb 01 '18 15:02 austenLacy

@pepincho I dont know whether this is actually a problem or not but when i comment firebase backhandler working for me. My current firebase version is "firebase": "^5.0.4", => for the lastest i havent try it yet when i downgrade to "firebase": "^4.13.1", it working perfectly with BackHandler

mhdanh avatar Jun 10 '18 10:06 mhdanh

@pepincho Hello, im having the same problem with back button. My problem is when i press the Device Back Button it Forces the app to close. I tried to create a new project and test each and every plugin i installed.

Device Back Button seems to be working fine to every plugin except when i import firebase from 'firebase' the Device Back Button never works. If you have fix to this, please share it

alz10 avatar Jun 12 '18 16:06 alz10

@maidanhcongtu DUUUUUUUUUUUUDE!!!!!!! You saved me. It worked now. I had to downgrade firebase to npm install [email protected] and the Device Back Button works for me now even without using BackHandler

alz10 avatar Jun 12 '18 16:06 alz10