How to get Battery Level in React Native App?


Share:
Published By: Admin, Published On: Jul 05, 2021, Category: React Native

Hi Guys,

Today, I will learn you how to get battery level in react native app. We will show example of battery level information in react native. You can easliy create react native battery level. First i will import Brightness namespace from expo-battery, after I will make battery level using in react native.

Step 1 - Create project

In the first step Run the following command for create project.

expo init MyWebtuts 
Step 2 - Installation of Dependency

In the step, Run the following command for installation of dependency.

To use Brightness you need to install expo-battery package.

To install this open the terminal and jump into your project

cd paper MyWebtuts 
Run the following command
yarn add expo-battery
Step 3 - App.js

In this step, You will open App.js file and put the code.

import * as React from 'react';
import * as Battery from 'expo-battery';
import { StyleSheet, Text, View } from 'react-native';

export default class App extends React.Component {
  state = {
    batteryLevel: null,
  };

  componentDidMount() {
    this._subscribe();
  }

  componentWillUnmount() {
    this._unsubscribe();
  }

  async _subscribe() {
    const batteryLevel = await Battery.getBatteryLevelAsync();
    this.setState({ batteryLevel });
    this._subscription = Battery.addBatteryLevelListener(({ batteryLevel }) => {
      this.setState({ batteryLevel });
      console.log('batteryLevel changed!', batteryLevel);
    });
  }

  _unsubscribe() {
    this._subscription && this._subscription.remove();
    this._subscription = null;
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>React Native Get Battery Level - MyWebtuts.com</Text>
        <Text>Current Battery Level: {this.state.batteryLevel}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 15,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Step 3 - Run project

In the last step run your project using bellow command.

expo start
Output

It will help you...

Share: