react-native 앱 종료 방법에 대해 포스팅 해보기로 한다.

 


react-native 앱 종료 방법은 2가지가 있다. 


1. react-native에서 제공해주는 BackHandler를 사용하는 법

import React, {useEffect} from 'react';
import {Text, View, StyleSheet, BackHandler, Alert} from 'react-native';

const App = () => {
  useEffect(() => {
    const backAction = () => {
      Alert.alert('Hold on!', 'Are you sure you want to go back?', [
        {
          text: 'Cancel',
          onPress: () => null,
          style: 'cancel',
        },
        {text: 'YES', onPress: () => BackHandler.exitApp()},
      ]);
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );

    return () => backHandler.remove();
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Click Back button!</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 18,
    fontWeight: 'bold',
  },
});

export default App;

주의해야할 점.
1. iOS는 적용이 안되고, Android에서만 작동한다. 
2. 앱을 완전히 kill 하는 것이 아닌 백그라운드 상태로 보낸다.

 


2. react-native-exit-app 라이브러리

  • iOS, Android에서 모두 작동한다.
  • 앱을 백그라운드 상태가 아닌 완전히 kill 한다.

 

설치

npm install react-native-exit-app --save
react-native link react-native-exit-app

Native 코드 수정 - Android

  • In the settings.gradle
      include ':react-native-exit-app', ':app'
      project(':react-native-exit-app').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-exit-app/android')
    

 

  • In the build.gradle
      implementation project(':react-native-exit-app')
    주의. react-native는 compile이 아닌 implementation을 쓴다.

 

  • In MainApplication.java
      import com.github.wumke.RNExitApp.RNExitAppPackage;
      ...
      @Override
      protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
          ...
          new RNExitAppPackage(),
          ...
        );
      }
      ...

사용법

import RNExitApp from 'react-native-exit-app';
...
RNExitApp.exitApp();
...

 

 

참고 https://github.com/wumke/react-native-exit-app

+ Recent posts