Home > other >  Screen awake, Idle timer
Screen awake, Idle timer

Time:10-25

I am working on a component which prevents screen going dark. I tested it and it is working fine, but the problem is even if I left the screen which that component is in, the screen doesn't turn dark, as if the component is working. How can I fix that? So when I leave the screen which this component is in, everything gets back to normal.

My code:

import React, { Component, useEffect } from 'react'
import { Text, View, StyleSheet, Button} from 'react-native'
import IdleTimerManager from 'react-native-idle-timer'

class SceenAwake extends Component {


    
    activate() {
        IdleTimerManager.setIdleTimerDisabled(true);
      }
      
      deactivate() {
        IdleTimerManager.setIdleTimerDisabled(false);
      }
    
render() {

    const {activateComponent} = this.props;
    
if (activateComponent == true ) {
    this.activate()
}
    return(
        <View style={styles.wrapper}>
     <Text>21th test</Text>
        </View>
    )
}

}
const styles = StyleSheet.create({
    wrapper: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
    }
})

export default SceenAwake

CodePudding user response:

first, convert your component to functional and If you are using React navigation then use useFocusEffect https://reactnavigation.org/docs/use-focus-effect/ and inside React.useCallback function return deactivate function.

CodePudding user response:

Since you used a class-based component to create SceenAwake, you need to create another component to determine the currently active screen status.

Here, I used a sample CheckIdle component:

import React, {useCallback} from 'react';
import { useFocusEffect } from '@react-navigation/native';
import IdleTimerManager from 'react-native-idle-timer'


function CheckIdle() {
  useFocusEffect(
    useCallback(() => {
      // invoke by mounting the screen

      // invoke by un mounting the screen
      return () => IdleTimerManager.setIdleTimerDisabled(false);
    }, [])
  );

  return null;
}

Now, a simple step left, add this CheckIdle component to the SceenAwake component:

import CheckIdle from 'path/to/the/file';
// rest of the codes ...

// rest of the codes ...

return(
  <View style={styles.wrapper}>
     <CheckIdle />
     <Text>21th test</Text>
  </View>
)
  • Related