Sri
Sri

Reputation: 181

React native listening to app foreground or background switching in Android

I have a requirement of pausing video and some other actions to perform when user clicks on home button or switch to another app using swiper action. I looked at react-native AppState, but it is not calling the event listener when home button clicked on android for some devices. Is there any compatibility minimum version requirements for the react-native app state to work?

The code I tried is as below

useEffect(() => {
    AppState.addEventListener("change", _handleAppStateChange);

    return () => {
      AppState.removeEventListener("change", _handleAppStateChange);
    };
}, []);

const _handleAppStateChange = (nextAppState: any) => {
    console.log(nextAppState);
};

The console is not printed when clicked on home button/Swiped to another app on some android devices. Is there anyway I can achieve this using react-native preferably without using any external libraries.

Upvotes: 1

Views: 6206

Answers (1)

Aditya
Aditya

Reputation: 3673

As for your requirement, in react-native, to detect is application is in foreground or in background, you don't need to add home-button listener, we can easily achieve this with the help of AppState, check below example,

_handleAppStateChange = (nextAppState: any) => {
    if (this.state.appState === "active" && nextAppState === "background") {

        // this condition calls when app goes in background mode
        // here you can detect application is in background, and you can pause your video

    } else if (this.state.appState === "background" && nextAppState === "active") {
    
        // this condition calls when app is in foreground mode
        // here you can detect application is in active state again, 
        // and if you want you can resume your video

    }
   this.setState({ appState: nextAppState });
};

You also need to attach AppState listener to application to detect application states, for example,

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

and detach app-state listener when application component unmount, for example,

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

Or if you are working with functional component you attach or detach app-state listener in useEffect, for example,

useEffect(() => {
    AppState.addEventListener("change", _handleAppStateChange);

    return () => {
       AppState.removeEventListener("change", _handleAppStateChange);
    };
}, []);

Upvotes: 4

Related Questions