简体   繁体   中英

Send a React-Native (Expo) app to the background on Android back button press with pure JavaScript?

I'd like to have the Android back button send the app to the background using pure JavaScript, but the only solutions I've been able to find require changes in Java and I'm trying to avoid ejecting from Expo just yet.

Is there a way to send an app to the background rather than exiting it.

Here is snack example. https://snack.expo.io/@nazrdogan/carefree-beef-jerky When you return false from Backhandler app will go background. if return true you can do your own logic.

 import * as React from 'react'; import { Text, View, StyleSheet, BackHandler } from 'react-native'; import { Constants } from 'expo'; // You can import from local files import AssetExample from './components/AssetExample'; // or any pure javascript modules available in npm import { Card, Button } from 'react-native-paper'; export default class App extends React.Component { componentDidMount() { BackHandler.addEventListener('hardwareBackPress', this.handleBackPress); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress); } handleBackPress = () => { //if you return false. it will goes background return false; }; render() { return ( <View style={styles.container}> <Text>Test</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', padding: 8, }, }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM