Example of React Native Keep Awake To Prevent Screen Sleep

Hello friends, In today’s tutorial we would learn about controlling mobile phone screen awake functionality. As we all know that we can se by default screen awake time or phone lock time in our phones. But in some of applications like YouTube or gaming apps the screen dose not sleep when we opens that applications for a long time period. This is because of they have disabled screen sleep on that particular time. There is a react native NPM library available known as react-native-keep-awake which gives us the same functionality we want here, you can visit their NPM page here. So in this tutorial we would learn about Example of React Native Keep Awake To Prevent Screen Sleep in Both Android and iOS mobile platforms.

Contents in this project Example of React Native Keep Awake To Prevent Screen Sleep :-

1. First of all we have to install the react-native-keep-awake NPM package in our react native project. So open your react native project Root directory in CMD or Terminal and execute below command.

Screenshot of CMD :-


Screenshot after done installation :-

2. The second step is only for iOS users. To link the installed library to our project we have to install PODS in our project. So execute below command to install PODS.

3. Now all the installation part has finished. Next step is to start coding for the app. So open your project’s main App.js file and import StyleSheet, Text, TouchableOpacity, View and Alert component.

4. Import KeepAwake component from ‘react-native-keep-awake’ package in our project.

5. Creating our main export default App functional component.

6. Crating a State named as awakeHolder with State update method setAwakeHolder with default value of False. Using this State we can enable and disable screen from sleeping.

7. Creating a function named as EnableAwake with value argument. In this function first we would check the value argument value and if the value is True then we would call the KeepAwake.activate() method to prevent scree from sleeping. We would also disable the screen awake using KeepAwake.deactivate() method.

8. Creating return() block, Now we would make 2 Touchable opacity buttons here and call above EnableAwake method with True and False argument to enable and disable screen from sleep.

9. Creating Style.

10. Complete Source Code for App.js file :-

Screenshots:-

Example of React Native Keep Awake To Prevent Screen Sleep