React Native: Double back press to Exit App

react native backhandler exit app
react-native-exit-app
react native app close event
react-navigation exit app
backhandler react native
react native minimize app
how to disable back button in react native
react native webview back button
How to exit application with twice clicking the back button without needing Redux

I was looking for a solution to limit the user and do not get out of the application with one click in react native.

import React, {Component} from 'react';
import {BackHandler, View, Dimensions, Animated, TouchableOpacity, Text} from 'react-native';

let {width, height} = Dimensions.get('window');


export default class App extends Component<Props> {

    state = {
        backClickCount: 0
    };

    constructor(props) {
        super(props);

        this.springValue = new Animated.Value(100) ;

    }

    componentWillMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton.bind(this));
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton.bind(this));
    }

    _spring() {
        this.setState({backClickCount: 1}, () => {
            Animated.sequence([
                Animated.spring(
                    this.springValue,
                    {
                        toValue: -.15 * height,
                        friction: 5,
                        duration: 300,
                        useNativeDriver: true,
                    }
                ),
                Animated.timing(
                    this.springValue,
                    {
                        toValue: 100,
                        duration: 300,
                        useNativeDriver: true,
                    }
                ),

            ]).start(() => {
                this.setState({backClickCount: 0});
            });
        });

    }


    handleBackButton = () => {
        this.state.backClickCount == 1 ? BackHandler.exitApp() : this._spring();

        return true;
    };


    render() {

        return (
            <View style={styles.container}>
                <Text>
                    container box
                </Text>

                <Animated.View style={[styles.animatedView, {transform: [{translateY: this.springValue}]}]}>
                    <Text style={styles.exitTitleText}>press back again to exit the app</Text>

                    <TouchableOpacity
                        activeOpacity={0.9}
                        onPress={() => BackHandler.exitApp()}
                    >
                        <Text style={styles.exitText}>Exit</Text>
                    </TouchableOpacity>

                </Animated.View>
            </View>
        );
    }
}


const styles = {
    container: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center"
    },
    animatedView: {
        width,
        backgroundColor: "#0a5386",
        elevation: 2,
        position: "absolute",
        bottom: 0,
        padding: 10,
        justifyContent: "center",
        alignItems: "center",
        flexDirection: "row",
    },
    exitTitleText: {
        textAlign: "center",
        color: "#ffffff",
        marginRight: 10,
    },
    exitText: {
        color: "#e5933a",
        paddingHorizontal: 10,
        paddingVertical: 3
    }
};

Run in snack.expo: https://snack.expo.io/HyhD657d7

How to implement double click android back to exit app · Issue #799 , exit-on-double-back. A react-native module to exit an app when the back button is pressed twice on android device. Note: This module only works with  Message to be displayed on the toast when the back button is pressed on the landing screen. Function to be called on double back press in the passed interval. If no function is passed, the app will exit. Function to be called on normal back presses of the application.

Below Code Explains itself. The trick is to have it in the Main AppContainer rather in every page

import {  Alert,  BackHandler,  ToastAndroid } from 'react-native';
import {  StackActions } from 'react-navigation';
// common statless class variable.
let backHandlerClickCount = 0;

class App extends React.Component {
    constructor(props) {
      super(props);
      // add listener to didFocus
      this._didFocusSubscription = props.navigation.addListener('didFocus', payload =>
        BackHandler.addEventListener('hardwareBackPress', () => this.onBackButtonPressAndroid(payload)));
    }

    // remove listener on unmount 
    componentWillUnmount() {
      if (this._didFocusSubscription) {
        this._didFocusSubscription.remove();
      }
    }

    onBackButtonPressAndroid = () => {
      const shortToast = message => {
        ToastAndroid.showWithGravityAndOffset(
          message,
          ToastAndroid.SHORT,
          ToastAndroid.BOTTOM,
          25,
          50
        );

        const {
          clickedPosition
        } = this.state;
        backHandlerClickCount += 1;
        if ((clickedPosition !== 1)) {
          if ((backHandlerClickCount < 2)) {
            shortToast('Press again to quit the application!');
          } else {
            BackHandler.exitApp();
          }
        }

        // timeout for fade and exit
        setTimeout(() => {
          backHandlerClickCount = 0;
        }, 2000);

        if (((clickedPosition === 1) &&
            (this.props.navigation.isFocused()))) {
          Alert.alert(
            'Exit Application',
            'Do you want to quit application?', [{
              text: 'Cancel',
              onPress: () => console.log('Cancel Pressed'),
              style: 'cancel'
            }, {
              text: 'OK',
              onPress: () => BackHandler.exitApp()
            }], {
              cancelable: false
            }
          );
        } else {
          this.props.navigation.dispatch(StackActions.pop({
            n: 1
          }));
        }
        return true;
      }

    }

rgabs/exit-on-double-back: A react-native module to exit an app , Exits app when back button is pressed twice in the passed interval on the index route of react-navigation. exit-on-double-back A react-native module to exit an app when the back button is pressed twice on android device. Note: This module only works with react-navigation (as of now) and your navigator should be integrated to redux store .

Another solution is to use the exit-on-double-back package.

exit-on-double-back, On HomeScreen, that is the root screen for our app, we will be handling the double back press to exit app, mount function will be called when  when running the app and go to the let's say Sign Up screen and touch the back in my mobile they will run the function and show the Alert to confirm, but now when I go to any other screen and touch the back they will I need to just back to the previous screen on every back BackHandler.exitApp(); runs, Although I write if the routname is SignUp just exit the app not other screens

Handle Android Back Button on React Native with grace., React Native and Android's Back Button. The default React Native behavior for the back button is that pressing the button will exit the app. Apple would reject your iOS app if you exit the app on button click. You could just show an alert without a button. User won't be able to dismiss the alert and enter the app rendering it useless. your solution makes sense but the issue is that Alerts cannot be displayed without buttons in react native.

Handling Android Back Button Events in React Native with Custom , When the user presses the Android hardware back button in React Native, react-​navigation will pop a screen or exit the app if there are no screens to pop. In some android games and app, when a user wants to exit the app or game a pop up will appear and ask the user to press the back button a number of times to exit the app. In some cases, this is to prevent unexpected app exit. The code below illustrates how to double click back button twice to exit an app in android. MainActivity.java.

Handling Android Back Button Press in React Native, back button, react-navigation will pop a screen or exit the app if there are no screens to On a back button press, you would first want the "selection mode" to be We make use of BackHandler which comes with react-native along with the​  If no subscription returns true or none are registered, it programmatically invokes the default back button functionality to exit the app. Warning for modal users: If your app shows an opened Modal , BackHandler will not publish any events ( see Modal docs ).

Comments
  • Ch Soal khubi ... Damet garm javab awli vase appam gereftam
  • tashakor baradar azizam @MoHammaDReZaDehGhani
  • Can you check this, Please Mr. Mahdi! stackoverflow.com/questions/55306718/…
  • can you check this, please !! stackoverflow.com/questions/55306718/…