React Native使用本机模块获取电池状态/电量

4urapxun  于 2022-11-30  发布在  React
关注(0)|答案(3)|浏览(250)

我正在写一个react原生应用程序来获取iOS和Android电池状态。我在网上搜索,发现很少有库可以获取手机的电池电量。
https://github.com/robinpowered/react-native-device-battery
https://github.com/remobile/react-native-battery-status
https://github.com/oojr/react-native-battery
当我尝试这样做时,每个库都有问题,而且在git hub上问开发人员问题时,没有太多的支持。
任何一个可以为我提供更好的解决方案或库,以获得IOS和Android的电池状态.
先谢了

92dk7w1h

92dk7w1h1#

我编写了自己的IOS和Android类来获取电池状态。如果有人对此感兴趣,
对于IOS,
1.在XCode中打开iOS项目
1.创建2个新文件,分别称为BatteryStatus. h和BatteryStatus. m
BatteryStatus.h文件应包含以下代码

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

@interface BatteryStatus : RCTEventEmitter <RCTBridgeModule>
@end

电池状态. m文件应该

#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.在react原生应用程序中,在js文件中添加以下代码

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

对于IOS以上代码是为我工作,以获得电池水平
对于安卓系统,
1.在Android Studio中打开Android项目

  1. Create a group call BatteryStatus and include 2 Files named , BatteryStatusModule.java and BatteryStatusPackage.java
    BatteryStatusModule.java Should contain 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 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 include following code
@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
        new MapsPackage(),
        new BatteryStatusPackage()
  );
}

1.在react原生应用程序中,在js文件中添加以下代码

import { NativeModules } from 'react-native';

 constructor(props) {
 super(props);

 this.state = {
   batteryLevel: null
 };
}

getBatteryLevel = (callback) => {
   NativeModules.BatteryStatus.getBatteryStatus(callback);
}

6.可以这样称呼它:

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

对于Android以上代码是为我工作,以获得电池水平
希望这将有助于一些人获得IOS和ANDROID的电池水平

lzfw57am

lzfw57am2#

我们可以使用react-native-device-info来获取任何设备的特定信息。
使用命令安装

npm install --save react-native-device-info
# or
yarn add react-native-device-info

通过getBatteryLevel()获取设备的电池电量,其值为0到1之间的浮点数。

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

备注:

在iOS模拟器上返回-1

ryoqjall

ryoqjall3#

只是对正确答案的一些补充。你必须覆盖BatteryStatus.m文件中的'supportedEvents'函数,使它像这样工作:

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

相关问题