LoginSignup
8
8

More than 3 years have passed since last update.

ReactNativeでアプリがForeground,Backgroundに移行するEventを拾って何かしたい。

Posted at

アプリがForegound⇔Inactive⇔Backgroundに移行するイベントをトリガーにして何かやりたいとき用に調べました。
AppStateというのを利用すれば取れるみたい。

この記事を参考(まんまですが)に、動作確認(とりあえずiOS)。

App.js
import React from 'react';
import { StyleSheet, Text, View, AppState } from 'react-native';
import { newTS } from 'uuid-js';

export default class App extends React.Component {

    constructor() {
        super();
        this.state = {
            appState: AppState.currentState,
        }
    }

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

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

    _handleAppStateChange = (nextAppState) => {

        this.setState({ appState: nextAppState });

        if (nextAppState === 'background') {
            console.log("Backgound mode");
        }

        if (nextAppState === 'active') {
            console.log("Foregound mode");
        }

        if (nextAppState === 'inactive') {
            console.log("Inactive mode");
        }
    }

    render() {
        return (
            <View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>
                <Text>Current state is : {this.state.appState}</Text>
            </View>
        );
    }
}
8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8