2016-08-15 88 views
18

我看到處處都找不到答案。如何檢測用戶何時嘗試關閉我的React Native應用程序(如在運行過程中,他們手動管理他們的應用程序並強制退出它)。我想在發生這種情況時添加註銷功能,但無法找到檢測它的方法。 AppState似乎只在應用程序進入和退出背景時才被檢測到。如何檢測React Native應用何時關閉(未暫停)?

+0

尋找的溶液太。你到目前爲止發現了什麼? –

回答

0

您無法阻止用戶關閉您的應用程序。 只有當你要關閉應用程序(你的應用程序的不活動狀態)時,你才能做的就是捕獲用戶。你可以嘗試去捕捉這個動作,並推送一些信息「不要關閉我,不要!」。

+7

他沒有要求阻止用戶關閉應用的方法。他詢問如何檢測應用關閉事件。 – Xiaoerge

3

看起來你可以檢測到以前的狀態並將其與下一個狀態進行比較。您無法檢測到該應用正在關閉並進入後臺,從我在網上可以找到的位置,但是您可以檢測它是否爲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> 
    ); 
    } 

} 
相關問題