programing

React Native 앱이 닫혔을 때(일시 중단되지 않았을 때) 어떻게 감지합니까?

sourcejob 2023. 2. 16. 21:37
반응형

React Native 앱이 닫혔을 때(일시 중단되지 않았을 때) 어떻게 감지합니까?

나는 모든 곳을 찾아봤지만 이에 대한 답을 찾을 수가 없어요.사용자가 React Native 앱을 닫으려고 할 때(프로세스 실행 중이고 사용자가 수동으로 앱을 관리하고 강제로 종료함)를 감지하려면 어떻게 해야 합니까?그럴 때 로그아웃 기능을 추가하고 싶은데 검출 방법을 찾을 수 없습니다. AppState앱이 백그라운드에서 가져오고 나가는 시간만 감지하는 것 같습니다.

이전 상태를 감지하고 다음 상태와 비교할 수 있을 것 같습니다.앱이 닫히는 것과 백그라운드로 이동하는 것은 온라인으로 확인할 수 있지만 앱이 닫히는 것은 감지할 수 없습니다.inactive(닫힘) 또는background.

React Native Docs의 예

import React, {Component} from 'react'
import {AppState, Text} from 'react-native'

class AppStateExample extends Component {

  state = {
    appState: AppState.currentState
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
    }
    this.setState({appState: nextAppState});
  }

  render() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }

}

를 사용하여useAppState훅을 눌러 앱 상태를 확인합니다.

앱을 닫으면 다음과 같은 상태가 됩니다.unknown다시 열면 돼요.이 배경화면에는background' or 'inactive'. So when it's unknown 앱이 닫히거나 최소화되거나 백그라운드에서 열리는 것을 알 수 있습니다.

웹 소켓을 사용하는 것이 좋습니다.그러면 다음과 같이 문제를 해결하는 데 도움이 됩니다.

반응 네이티브 앱

import React from 'react';
const io = require('socket.io-client/dist/socket.io');

const App = ()=>{
    React.useEffect(()=>{
        // connect to web socket
        window.appSocket = io.connect(`<server-origin>/?token=<string>&userAppId=<string>`);
        window.appSocket.on('connect',()=>{
            // do what you line
        })
    },[])

    ...
}
export default App; 

익스프레스 서버 측

const express   = require('express');
const server    = express();
const http      = require('http').Server(server);
const io        = require('socket.io')(http);
io.on('connection',(socket)=>{ // this callback function for each web socket connection
    let { token , userAppId } = socket.handshake.query;
    if( userAppId ){ 
        console.log(`${userAppId} online`)
        socket.on('disconnect',(resean)=>{
            console.log(`${userAppId} shut down`)
        })
    }
});

자세한 것은 소켓을 참조해 주세요.이오

방금 같은 문제에 부딪혔어요받아들여진 답변은 실제로 OP에 요구된 대로 수행되지 않습니다.

해킹 솔루션은 새로 열었을 때 응용 프로그램이 처음 열리는 화면에 플래그를 설정하고, 백그라운드로 막 열었을 때는 해당 화면을 표시하지 않는 것입니다.

매우 우아하지 않고 예제 코드를 보여줄 수는 없지만, 제 특정 문제를 해결합니다.

간단한 방법으로 루트 컴포넌트 내의 componentWillUnmount()를 사용하여 앱이 닫혔음을 검출할 수 있습니다.앱이 닫힐 때만 루트 구성 요소의 마운트를 해제하기 때문입니다.:)

언급URL : https://stackoverflow.com/questions/38962034/how-to-detect-when-a-react-native-app-is-closed-not-suspended

반응형