Coder Social home page Coder Social logo

react-native-device-battery's Introduction

react-native-device-battery

Get and observe the devices battery level and charging status

Installation

Install the node module

npm install react-native-device-battery --save

iOS

TBD

Android

Add the following to android/settings.grade

include ':react-native-device-battery'
project(':react-native-device-battery').projectDir = new File(settingsDir, '../node_modules/react-native-device-battery/android')

Add the following to android/app/build.gradle

compile project(':react-native-device-battery')

Register the module in MainActivity.java

import com.robinpowered.react.battery.DeviceBatteryPackage;  // <--- import

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
  ......

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mReactRootView = new ReactRootView(this);

    mReactInstanceManager = ReactInstanceManager.builder()
      .setApplication(getApplication())
      .setBundleAssetName("index.android.bundle")
      .setJSMainModuleName("index.android")
      .addPackage(new MainReactPackage())
      .addPackage(new DeviceBatteryPackage()) // <------ add this line to yout MainActivity class
      .setUseDeveloperSupport(BuildConfig.DEBUG)
      .setInitialLifecycleState(LifecycleState.RESUMED)
      .build();

    mReactRootView.startReactApplication(mReactInstanceManager, "AndroidRNSample", null);

    setContentView(mReactRootView);
  }

  ......

}

Example Usage

import DeviceBattery from 'react-native-device-battery';

// get the battery level
DeviceBattery.getBatteryLevel().then(level => {
  console.log(level); // between 0 and 1
});

// check if the device is charging
DeviceBattery.isCharging().then(isCharging => {
  console.log(isCharging) // true or false
});

// as a listener
var onBatteryStateChanged = (state) => {
  console.log(state) // {level: 0.95, charging: true}
};

// to attach a listener
DeviceBattery.addListener(onBatteryStateChanged);

// to remove a listener
DeviceBattery.removeListener(onBatteryStateChanged);

react-native-device-battery's People

Contributors

alextsg avatar atticoos avatar cchestnut91 avatar christophermark avatar jutaz avatar nivnahmias avatar yinghang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-device-battery's Issues

Error during compilation

/Users/titto/workspace/babbo/android/app/src/main/java/com/babbo/MainActivity.java:34: error: constructor DeviceBatteryPackage in class DeviceBatteryPackage cannot be applied to given types;
.addPackage(new DeviceBatteryPackage())
^
required: Activity
found: no arguments
reason: actual and formal argument lists differ in length
1 error
:app:compileDebugJavaWithJavac FAILED

android - change dependency of react native version to '+'

https://github.com/robinpowered/react-native-device-battery/blob/master/android/build.gradle#L33

As in all other react native packages it should be set to '+'.
If there's a minimum react natuve version you should write it in the readme file.
Currently, it is causing an unnecessary download of react native 0.15 to the gradle cache (Although the app is running perfectly because it is overridden).

change compile 'com.facebook.react:react-native:0.15.+'
to compile 'com.facebook.react:react-native:+'

Publish recent improvements to npm

Thanks for providing this useful module. I noticed that the npm package was last updated 9 months ago, whereas several improvements have been commited to this repository more recently. May I suggest you publish a new version to the npm?

Is this repo still maintained?

I was just wondering if this repo is still maintained. I need the battery status listener, which we have here. But the remove listener is missing and only needs to be merged to the lib.

If it's not maintained, can anybody recommend another package with that functionality?

removeListener method missing

Hi
The docs refer to DeviceBattery.removeListener(onBatteryStateChanged);, but this method seems to be missing from the code and throws a TypeError.

getBatteryLevel doesn't get an updated battery level on Android

Hey guys,

I've been trying to use your library to take snapshots of a device's battery drain while apps are running in the background on Android. Unfortunately, it seems that .getBatteryLevel() doesn't return an updated battery level even when called 30-60 minutes later with clear battery loss of 4-5%. I'm keeping the app in the foreground, so I don't think that background state would be an issue.

I noticed that Intent.ACTION_BATTERY_CHANGED is a sticky intent, so I thought that the sticky intent caching values could be the issue. I tried adding changing `public void getBatteryLevel(Promise promise) to:

public void getBatteryLevel(Promise promise) {
   if (batteryStatus != null) {
      float batteryPercentage = getBatteryPrecentageFromIntent(batteryStatus);
      promise.resolve((double) batteryPercentage);

      getReactApplicationContext().removeStickyBroadcast(batteryStatus);
      IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
      batteryStatus = getReactApplicationContext().registerReceiver(batteryStateReceiver, filter);
   } else {
      promise.reject("Battery manager is not active");
   }
}

I was hoping that removing the intent and reregistering it would invalidate the cache, but it seems it doesn't or that this is not the source of the problem.

The only way I could get getBatteryLevel() to detect a new value was by closing the app and reinstalling or by reloading the JS. Even by doing this I could only get getBatteryLevel() to return a new value when there was a significant change (from .28000000011920929 to .28999999165534973), but finer grained changes were impossible to detect.

I'm aware that this may be an Android API problem and not a problem with your code. Have you had any experience dealing with this kind of issue?

Thanks!

Battery doest not work when app in background

Battery doest not work in android when app in background (minimized).
I have error:

error Error: Battery manager is not active
    at createErrorFromErrorData (E:\projects\project_name\node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:123)
    at E:\projects\project_name\node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:80
    at MessageQueue.__invokeCallback (E:\projects\project_name\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:400)
    at E:\projects\project_name\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:139
    at MessageQueue.__guardSafe (E:\projects\project_name\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:316)
    at MessageQueue.invokeCallbackAndReturnFlushedQueue (E:\projects\project_name\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:138)
    at debuggerWorker.js:72

Please fix it.
I use
"react-native": "0.54.4",
"react-native-background-task": "0.2.1"

some code:

file battery
export const getLevel = onLevel => {
  DeviceBattery.getBatteryLevel().then(level => {
    const battery_level = Math.round(level * 100);
    onLevel(battery_level);
  });
}

file in use
import * as Battery from '../battery';

try {
        DeviceBattery.getBatteryLevel().then(level => {
            const battery_l = Math.round(level * 100);
        });
 } catch (e) {
        console.log("error", e);
}

Does this package work in the iOS simulator?

Package works on Android for me, but on iOS the listener never fires and getting the device battery returns -1. Is this a configuration problem on my end, or is the simulator not have a battery to track?

getBatteryLevel & isCharging don't update result

Calling the 2 main functions getBatteryLevel & isCharging don't change result after the first call.
For example, calling isCharging when the phone is connected will return true, disconnecting the phone and calling the function again will still return true.

Using the listener the disconnect event is captured but i would prefer to just use the 2 functions.
I'm not sure what's causing this issue.

Thanks

Readme not up to date?

Hi,

I am not sure, if I am missing something. But, my MainActivity.java file (Android) does not look like the one in your Readme:

This is yours:

import com.robinpowered.react.battery.DeviceBatteryPackage;  // <--- import

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
  ......

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mReactRootView = new ReactRootView(this);

    mReactInstanceManager = ReactInstanceManager.builder()
      .setApplication(getApplication())
      .setBundleAssetName("index.android.bundle")
      .setJSMainModuleName("index.android")
      .addPackage(new MainReactPackage())
      .addPackage(new DeviceBatteryPackage()) // <------ add this line to yout MainActivity class
      .setUseDeveloperSupport(BuildConfig.DEBUG)
      .setInitialLifecycleState(LifecycleState.RESUMED)
      .build();

    mReactRootView.startReactApplication(mReactInstanceManager, "AndroidRNSample", null);

    setContentView(mReactRootView);
  }

  ......

}

This is mine:

package com.xxxxx;

import com.facebook.react.ReactActivity;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "xxxxxx";
    }
}

When I try to build the app I see errors like:

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
                                  ^
  symbol: class Activity

My questions are:

  • do I really need to add onCreate here and not in the MainApplication.java file instead?
  • does it work with react-native 0.50.3?

Thanks for your help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.