how can I call a funcation when I press home screen button in react native

Viewed 484

I have a sound player app and I want it to stop playing current song when user presses home screen button in android, actually sound is playing when pressing the home screen.

I use the componentWillUnmount for back button but for home screen button I don't know what should I use?

1 Answers

You need to user AppState which help you to find in which state your application is. You can do your logic when State is background

Here is sample code:

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>
    );
  }

}

App States

active - The app is running in the foreground

background - The app is running in the background. The user is either:
in another app
on the home screen
[Android] on another Activity (even if it was launched by your app)

inactive - This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the Multitasking view or in the event of an incoming call
Related