React Native Get Battery Status / Charge Using Native Modules

I am writing a reciprocal native application to get the status of IOS and Android Battery. I browse the web and find several libraries that can get the phone’s battery level.

https://github.com/robinpowered/react-native-device-battery

https://github.com/remobile/react-native-battery-status

https://github.com/oojr/react-native-battery

Each library has problems when I try, and don't really support the developer by asking a question about the git hub.

Can someone provide me a better solution or library to get the battery status of IOS and Android.

Thank you in advance

+8
source share
3 answers

I wrote my own iOS and Android classes to get battery status. Here are the steps if anyone is interested in this,

For iOS,

  • Open your iOS project in Xcode
  • Create 2 new files to call BatteryStatus.h and BatteryStatus.m

The BatteryStatus.h file should contain the following code

#import <Foundation/Foundation.h> #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> @interface BatteryStatus : RCTEventEmitter <RCTBridgeModule> @end 

The BatteryStatus.m file should

 #import "BatteryStatus.h" @implementation BatteryStatus RCT_EXPORT_MODULE(BatteryStatus) - (instancetype)init { if ((self = [super init])) { [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; } return self; } RCT_EXPORT_METHOD(hide) { } RCT_EXPORT_METHOD(updateBatteryLevel:(RCTResponseSenderBlock)callback) { callback(@[[self getBatteryStatus]]); } //manually get battery status by calling following method -(NSDictionary*)getBatteryStatus { float batteryLevel = [UIDevice currentDevice].batteryLevel; NSObject* currentLevel = nil; currentLevel = [NSNumber numberWithFloat:(batteryLevel * 100)]; NSMutableDictionary* batteryData = [NSMutableDictionary dictionaryWithCapacity:2]; [batteryData setObject:currentLevel forKey:@"level"]; return batteryData; } @end 
  1. Inside your response to your own application inside your js file add the following code

     import { NativeModules } from 'react-native'; constructor(props) { super(props); this.state = { batteryLevel: null, }; } componentDidMount() { NativeModules.BatteryStatus.updateBatteryLevel((info) => { //console.log(info.level) const level = Math.ceil(info.level); this.setState({ batteryLevel: level}); }); } 

For iOS above, the code works for me to get the battery level

For Android,

  • Open an Android project in Android Studio
  • Create a BatteryStatus batch call and include 2 files named BatteryStatusModule.java and BatteryStatusPackage.java.

BatteryStatusModule.java Must contain the following code

 package com.yourproject.BatteryStatus; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; public class BatteryStatusModule extends ReactContextBaseJavaModule { public BatteryStatusModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "BatteryStatus"; } @ReactMethod public void getBatteryStatus(Callback successCallback) { Intent batteryIntent = getCurrentActivity().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); if(level == -1 || scale == -1) { level = 0; } //System.out.print("battery level"); //System.out.print(level); successCallback.invoke(null ,((float)level / (float)scale) * 100.0f); } } 

BatteryStatusPackage.java should contain the following code

  package com.yourproject.BatteryStatus; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class BatteryStatusPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new BatteryStatusModule(reactContext)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } } 
  1. Inside MainApplication.java there is the following code

     @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new MapsPackage(), new BatteryStatusPackage() ); } 
  2. Inside your response to your own application inside your js file add the following code

      import { NativeModules } from 'react-native'; constructor(props) { super(props); this.state = { batteryLevel: null }; } getBatteryLevel = (callback) => { NativeModules.BatteryStatus.getBatteryStatus(callback); } 

6.Call is something like this:

 componentDidMount() { this.getBatteryLevel((batteryLevel) => { console.log(batteryLevel); }); } 

For Android above, the code works for me to get the battery level

Hope this helps someone get battery level for iOS and ANDROID

+8
source

We can use react-native-device-info to get information specific to any device.

Install using the command

 npm install --save react-native-device-info 

Get the device’s battery level as a floating-point number in getBatteryLevel() from 0 to 1 using getBatteryLevel() .

 DeviceInfo.getBatteryLevel().then(batteryLevel => { // 0.759999 }); 

Remarks:

Returns -1 on iOS simulator

+3
source

Just add the correct answer. You must override the supportedEvents function in the BatteryStatus.m file so that it works as follows:

 -(NSArray<NSString *> *)supportedEvents{ return @[@"level"]; } 
+1
source

Source: https://habr.com/ru/post/1269511/


All Articles