├── .gitignore ├── README.md ├── android ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── robinpowered │ └── react │ └── battery │ ├── DeviceBatteryModule.java │ └── DeviceBatteryPackage.java ├── index.js ├── ios ├── DeviceBattery.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcuserdata │ │ │ └── ajwhite.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ └── ajwhite.xcuserdatad │ │ └── xcschemes │ │ ├── DeviceBattery.xcscheme │ │ └── xcschememanagement.plist └── DeviceBattery │ ├── DeviceBattery.h │ └── DeviceBattery.m ├── package.json └── react-native-device-battery.podspec /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # Xcode 6 | # 7 | build/ 8 | *.pbxuser 9 | !default.pbxuser 10 | *.mode1v3 11 | !default.mode1v3 12 | *.mode2v3 13 | !default.mode2v3 14 | *.perspectivev3 15 | !default.perspectivev3 16 | xcuserdata 17 | *.xccheckout 18 | *.moved-aside 19 | DerivedData 20 | *.hmap 21 | *.ipa 22 | *.xcuserstate 23 | project.xcworkspace 24 | ios/Pods 25 | ios/Podfile.local 26 | 27 | !ios/Pods/Target\ Support\ Files/Pods/Pods.*.xcconfig 28 | 29 | # Android/IJ 30 | # 31 | .idea 32 | .gradle 33 | local.properties 34 | *.iml 35 | *.iws 36 | *.ipr 37 | 38 | # node.js 39 | # 40 | node_modules/ 41 | npm-debug.log 42 | 43 | Makefile 44 | 45 | .tmp 46 | 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-native-device-battery 2 | 3 | Get and observe the devices battery level and charging status 4 | 5 | 6 | ## Installation 7 | 8 | Install the node module 9 | ``` 10 | npm install react-native-device-battery --save 11 | ``` 12 | 13 | ### iOS 14 | TBD 15 | 16 | ### Android 17 | Add the following to `android/settings.grade` 18 | ``` 19 | include ':react-native-device-battery' 20 | project(':react-native-device-battery').projectDir = new File(settingsDir, '../node_modules/react-native-device-battery/android') 21 | ``` 22 | 23 | Add the following to `android/app/build.gradle` 24 | ``` 25 | compile project(':react-native-device-battery') 26 | ``` 27 | 28 | Register the module in `MainActivity.java` 29 | ```java 30 | import com.robinpowered.react.battery.DeviceBatteryPackage; // <--- import 31 | 32 | public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler { 33 | ...... 34 | 35 | @Override 36 | protected void onCreate(Bundle savedInstanceState) { 37 | super.onCreate(savedInstanceState); 38 | mReactRootView = new ReactRootView(this); 39 | 40 | mReactInstanceManager = ReactInstanceManager.builder() 41 | .setApplication(getApplication()) 42 | .setBundleAssetName("index.android.bundle") 43 | .setJSMainModuleName("index.android") 44 | .addPackage(new MainReactPackage()) 45 | .addPackage(new DeviceBatteryPackage()) // <------ add this line to yout MainActivity class 46 | .setUseDeveloperSupport(BuildConfig.DEBUG) 47 | .setInitialLifecycleState(LifecycleState.RESUMED) 48 | .build(); 49 | 50 | mReactRootView.startReactApplication(mReactInstanceManager, "AndroidRNSample", null); 51 | 52 | setContentView(mReactRootView); 53 | } 54 | 55 | ...... 56 | 57 | } 58 | ``` 59 | 60 | 61 | ## Example Usage 62 | ```js 63 | import DeviceBattery from 'react-native-device-battery'; 64 | 65 | // get the battery level 66 | DeviceBattery.getBatteryLevel().then(level => { 67 | console.log(level); // between 0 and 1 68 | }); 69 | 70 | // check if the device is charging 71 | DeviceBattery.isCharging().then(isCharging => { 72 | console.log(isCharging) // true or false 73 | }); 74 | 75 | // as a listener 76 | var onBatteryStateChanged = (state) => { 77 | console.log(state) // {level: 0.95, charging: true} 78 | }; 79 | 80 | // to attach a listener 81 | DeviceBattery.addListener(onBatteryStateChanged); 82 | 83 | // to remove a listener 84 | DeviceBattery.removeListener(onBatteryStateChanged); 85 | ``` 86 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | } 5 | 6 | dependencies { 7 | classpath 'com.android.tools.build:gradle:1.3.1' 8 | } 9 | } 10 | 11 | apply plugin: 'com.android.library' 12 | 13 | def safeExtGet(prop, fallback) { 14 | rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback 15 | } 16 | 17 | android { 18 | compileSdkVersion safeExtGet('compileSdkVersion', '23') 19 | buildToolsVersion safeExtGet('buildToolsVersion', '23.0.1') 20 | 21 | defaultConfig { 22 | minSdkVersion safeExtGet('minSdkVersion', '16') 23 | targetSdkVersion safeExtGet('targetSdkVersion', '22') 24 | versionCode 1 25 | versionName "1.0" 26 | } 27 | lintOptions { 28 | abortOnError false 29 | } 30 | } 31 | 32 | repositories { 33 | mavenCentral() 34 | } 35 | 36 | dependencies { 37 | implementation 'com.facebook.react:react-native:+' 38 | } 39 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robinpowered/react-native-device-battery/ead638e641aeccf85af76bd9b4d2aded448df352/android/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Apr 10 15:27:10 PDT 2013 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip 7 | -------------------------------------------------------------------------------- /android/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /android/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /android/src/main/java/com/robinpowered/react/battery/DeviceBatteryModule.java: -------------------------------------------------------------------------------- 1 | package com.robinpowered.react.battery; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.content.IntentFilter; 6 | import android.content.BroadcastReceiver; 7 | import android.os.BatteryManager; 8 | import android.util.Log; 9 | 10 | import com.facebook.react.bridge.ReactApplicationContext; 11 | import com.facebook.react.bridge.ReactContextBaseJavaModule; 12 | import com.facebook.react.bridge.WritableMap; 13 | import com.facebook.react.bridge.WritableNativeMap; 14 | import com.facebook.react.bridge.ReactMethod; 15 | import com.facebook.react.bridge.ReadableArray; 16 | import com.facebook.react.bridge.Promise; 17 | import com.facebook.react.modules.core.DeviceEventManagerModule; 18 | import com.facebook.react.modules.core.RCTNativeAppEventEmitter; 19 | import com.facebook.react.bridge.LifecycleEventListener; 20 | 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | 24 | import javax.annotation.Nullable; 25 | 26 | // @link http://developer.android.com/training/monitoring-device-state/battery-monitoring.html 27 | public class DeviceBatteryModule extends ReactContextBaseJavaModule 28 | implements LifecycleEventListener { 29 | 30 | public static final String EVENT_NAME = "batteryChange"; 31 | public static final String IS_CHARGING_KEY = "charging"; 32 | public static final String BATTERY_LEVEL_KEY = "level"; 33 | 34 | private Intent batteryStatus = null; 35 | private @Nullable PowerConnectionReceiver batteryStateReceiver; 36 | 37 | 38 | public DeviceBatteryModule(ReactApplicationContext reactApplicationContext) { 39 | super(reactApplicationContext); 40 | } 41 | 42 | private float getBatteryPrecentageFromIntent(Intent intent) { 43 | int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); 44 | int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); 45 | return level / (float) scale; 46 | } 47 | 48 | private boolean getIsChangingFromIntent(Intent intent) { 49 | int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); 50 | return ( 51 | status == BatteryManager.BATTERY_STATUS_CHARGING || 52 | status == BatteryManager.BATTERY_STATUS_FULL 53 | ); 54 | } 55 | 56 | private WritableNativeMap getJSMap (Intent intent) { 57 | float batteryPercentage = getBatteryPrecentageFromIntent(intent); 58 | boolean isCharging = getIsChangingFromIntent(intent); 59 | WritableNativeMap params = new WritableNativeMap(); 60 | params.putBoolean(IS_CHARGING_KEY, isCharging); 61 | params.putDouble(BATTERY_LEVEL_KEY, (double) batteryPercentage); 62 | return params; 63 | } 64 | 65 | public void notifyBatteryStateChanged(Intent intent) { 66 | batteryStatus = intent; 67 | // only emit an event if the Catalyst instance is avialable 68 | if (getReactApplicationContext().hasActiveCatalystInstance()) { 69 | WritableNativeMap params = getJSMap(intent); 70 | try { 71 | getReactApplicationContext() 72 | .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) 73 | .emit(EVENT_NAME, params); 74 | } catch (Exception e) { 75 | Log.e(getName(), "notifyBatteryStateChanged called before bundle loaded"); 76 | } 77 | } 78 | } 79 | 80 | @Override 81 | public Map getConstants() { 82 | final Map constants = new HashMap<>(); 83 | constants.put("BATTERY_CHANGE_EVENT", EVENT_NAME); 84 | return constants; 85 | } 86 | 87 | @ReactMethod 88 | public void getBatteryLevel(Promise promise) { 89 | if (batteryStatus != null) { 90 | float batteryPercentage = getBatteryPrecentageFromIntent(batteryStatus); 91 | promise.resolve((double) batteryPercentage); 92 | } else { 93 | promise.reject("Battery manager is not active"); 94 | } 95 | } 96 | 97 | @ReactMethod 98 | public void isCharging(Promise promise) { 99 | if (batteryStatus != null) { 100 | boolean isCharging = getIsChangingFromIntent(batteryStatus); 101 | promise.resolve(isCharging); 102 | } else { 103 | promise.reject("Battery manager is not active"); 104 | } 105 | } 106 | 107 | private void maybeRegisterReceiver() { 108 | if (batteryStateReceiver != null) { 109 | return; 110 | } 111 | batteryStateReceiver = new PowerConnectionReceiver(); 112 | IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); 113 | batteryStatus = getReactApplicationContext().registerReceiver(batteryStateReceiver, filter); 114 | } 115 | 116 | private void maybeUnregisterReceiver() { 117 | if (batteryStateReceiver == null) { 118 | return; 119 | } 120 | getReactApplicationContext().unregisterReceiver(batteryStateReceiver); 121 | batteryStateReceiver = null; 122 | batteryStatus = null; 123 | } 124 | 125 | @Override 126 | public String getName() { 127 | return "DeviceBattery"; 128 | } 129 | 130 | @Override 131 | public void initialize() { 132 | getReactApplicationContext().addLifecycleEventListener(this); 133 | maybeRegisterReceiver(); 134 | } 135 | 136 | @Override 137 | public void onHostResume() { 138 | maybeRegisterReceiver(); 139 | } 140 | @Override 141 | public void onHostPause() { 142 | maybeUnregisterReceiver(); 143 | } 144 | @Override 145 | public void onHostDestroy() { 146 | maybeUnregisterReceiver(); 147 | } 148 | 149 | class PowerConnectionReceiver extends BroadcastReceiver { 150 | private DeviceBatteryModule mBatteryModule; 151 | 152 | @Override 153 | public void onReceive(Context context, Intent intent) { 154 | notifyBatteryStateChanged(intent); 155 | } 156 | } 157 | 158 | } 159 | -------------------------------------------------------------------------------- /android/src/main/java/com/robinpowered/react/battery/DeviceBatteryPackage.java: -------------------------------------------------------------------------------- 1 | package com.robinpowered.react.battery; 2 | 3 | import android.app.Activity; 4 | 5 | import com.facebook.react.ReactPackage; 6 | import com.facebook.react.bridge.JavaScriptModule; 7 | import com.facebook.react.bridge.NativeModule; 8 | import com.facebook.react.bridge.ReactApplicationContext; 9 | import com.facebook.react.uimanager.ViewManager; 10 | 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.Collections; 14 | import java.util.List; 15 | 16 | public class DeviceBatteryPackage implements ReactPackage { 17 | @Override 18 | public List createNativeModules(ReactApplicationContext reactApplicationContext) { 19 | List modules = new ArrayList(); 20 | modules.add(new DeviceBatteryModule(reactApplicationContext)); 21 | return modules; 22 | } 23 | 24 | @Override 25 | public List createViewManagers(ReactApplicationContext reactApplicationContext) { 26 | return Arrays.asList(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var {NativeModules, NativeEventEmitter} = require('react-native'); 2 | var {DeviceBattery} = NativeModules; 3 | 4 | const batteryEventEmitter = new NativeEventEmitter(DeviceBattery); 5 | 6 | export default { 7 | isCharging: DeviceBattery.isCharging, 8 | getBatteryLevel: DeviceBattery.getBatteryLevel, 9 | addListener: callback => batteryEventEmitter.addListener(DeviceBattery.BATTERY_CHANGE_EVENT, callback), 10 | removeListener: callback => batteryEventEmitter.removeListener(DeviceBattery.BATTERY_CHANGE_EVENT, callback) 11 | }; 12 | -------------------------------------------------------------------------------- /ios/DeviceBattery.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 5DFE59151C0E9C0800784FDF /* DeviceBattery.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = 5DFE59141C0E9C0800784FDF /* DeviceBattery.h */; }; 11 | 5DFE59171C0E9C0800784FDF /* DeviceBattery.m in Sources */ = {isa = PBXBuildFile; fileRef = 5DFE59161C0E9C0800784FDF /* DeviceBattery.m */; }; 12 | /* End PBXBuildFile section */ 13 | 14 | /* Begin PBXCopyFilesBuildPhase section */ 15 | 5DFE590F1C0E9C0800784FDF /* CopyFiles */ = { 16 | isa = PBXCopyFilesBuildPhase; 17 | buildActionMask = 2147483647; 18 | dstPath = "include/$(PRODUCT_NAME)"; 19 | dstSubfolderSpec = 16; 20 | files = ( 21 | 5DFE59151C0E9C0800784FDF /* DeviceBattery.h in CopyFiles */, 22 | ); 23 | runOnlyForDeploymentPostprocessing = 0; 24 | }; 25 | /* End PBXCopyFilesBuildPhase section */ 26 | 27 | /* Begin PBXFileReference section */ 28 | 5DFE59111C0E9C0800784FDF /* libDeviceBattery.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libDeviceBattery.a; sourceTree = BUILT_PRODUCTS_DIR; }; 29 | 5DFE59141C0E9C0800784FDF /* DeviceBattery.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = DeviceBattery.h; sourceTree = ""; }; 30 | 5DFE59161C0E9C0800784FDF /* DeviceBattery.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = DeviceBattery.m; sourceTree = ""; }; 31 | /* End PBXFileReference section */ 32 | 33 | /* Begin PBXFrameworksBuildPhase section */ 34 | 5DFE590E1C0E9C0800784FDF /* Frameworks */ = { 35 | isa = PBXFrameworksBuildPhase; 36 | buildActionMask = 2147483647; 37 | files = ( 38 | ); 39 | runOnlyForDeploymentPostprocessing = 0; 40 | }; 41 | /* End PBXFrameworksBuildPhase section */ 42 | 43 | /* Begin PBXGroup section */ 44 | 5DFE59081C0E9C0800784FDF = { 45 | isa = PBXGroup; 46 | children = ( 47 | 5DFE59131C0E9C0800784FDF /* DeviceBattery */, 48 | 5DFE59121C0E9C0800784FDF /* Products */, 49 | ); 50 | sourceTree = ""; 51 | }; 52 | 5DFE59121C0E9C0800784FDF /* Products */ = { 53 | isa = PBXGroup; 54 | children = ( 55 | 5DFE59111C0E9C0800784FDF /* libDeviceBattery.a */, 56 | ); 57 | name = Products; 58 | sourceTree = ""; 59 | }; 60 | 5DFE59131C0E9C0800784FDF /* DeviceBattery */ = { 61 | isa = PBXGroup; 62 | children = ( 63 | 5DFE59141C0E9C0800784FDF /* DeviceBattery.h */, 64 | 5DFE59161C0E9C0800784FDF /* DeviceBattery.m */, 65 | ); 66 | path = DeviceBattery; 67 | sourceTree = ""; 68 | }; 69 | /* End PBXGroup section */ 70 | 71 | /* Begin PBXNativeTarget section */ 72 | 5DFE59101C0E9C0800784FDF /* DeviceBattery */ = { 73 | isa = PBXNativeTarget; 74 | buildConfigurationList = 5DFE591A1C0E9C0800784FDF /* Build configuration list for PBXNativeTarget "DeviceBattery" */; 75 | buildPhases = ( 76 | 5DFE590D1C0E9C0800784FDF /* Sources */, 77 | 5DFE590E1C0E9C0800784FDF /* Frameworks */, 78 | 5DFE590F1C0E9C0800784FDF /* CopyFiles */, 79 | ); 80 | buildRules = ( 81 | ); 82 | dependencies = ( 83 | ); 84 | name = DeviceBattery; 85 | productName = DeviceBattery; 86 | productReference = 5DFE59111C0E9C0800784FDF /* libDeviceBattery.a */; 87 | productType = "com.apple.product-type.library.static"; 88 | }; 89 | /* End PBXNativeTarget section */ 90 | 91 | /* Begin PBXProject section */ 92 | 5DFE59091C0E9C0800784FDF /* Project object */ = { 93 | isa = PBXProject; 94 | attributes = { 95 | LastUpgradeCheck = 0810; 96 | ORGANIZATIONNAME = "Atticus White"; 97 | TargetAttributes = { 98 | 5DFE59101C0E9C0800784FDF = { 99 | CreatedOnToolsVersion = 7.1.1; 100 | }; 101 | }; 102 | }; 103 | buildConfigurationList = 5DFE590C1C0E9C0800784FDF /* Build configuration list for PBXProject "DeviceBattery" */; 104 | compatibilityVersion = "Xcode 3.2"; 105 | developmentRegion = English; 106 | hasScannedForEncodings = 0; 107 | knownRegions = ( 108 | en, 109 | ); 110 | mainGroup = 5DFE59081C0E9C0800784FDF; 111 | productRefGroup = 5DFE59121C0E9C0800784FDF /* Products */; 112 | projectDirPath = ""; 113 | projectRoot = ""; 114 | targets = ( 115 | 5DFE59101C0E9C0800784FDF /* DeviceBattery */, 116 | ); 117 | }; 118 | /* End PBXProject section */ 119 | 120 | /* Begin PBXSourcesBuildPhase section */ 121 | 5DFE590D1C0E9C0800784FDF /* Sources */ = { 122 | isa = PBXSourcesBuildPhase; 123 | buildActionMask = 2147483647; 124 | files = ( 125 | 5DFE59171C0E9C0800784FDF /* DeviceBattery.m in Sources */, 126 | ); 127 | runOnlyForDeploymentPostprocessing = 0; 128 | }; 129 | /* End PBXSourcesBuildPhase section */ 130 | 131 | /* Begin XCBuildConfiguration section */ 132 | 5DFE59181C0E9C0800784FDF /* Debug */ = { 133 | isa = XCBuildConfiguration; 134 | buildSettings = { 135 | ALWAYS_SEARCH_USER_PATHS = NO; 136 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 137 | CLANG_CXX_LIBRARY = "libc++"; 138 | CLANG_ENABLE_MODULES = YES; 139 | CLANG_ENABLE_OBJC_ARC = YES; 140 | CLANG_WARN_BOOL_CONVERSION = YES; 141 | CLANG_WARN_CONSTANT_CONVERSION = YES; 142 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 143 | CLANG_WARN_EMPTY_BODY = YES; 144 | CLANG_WARN_ENUM_CONVERSION = YES; 145 | CLANG_WARN_INFINITE_RECURSION = YES; 146 | CLANG_WARN_INT_CONVERSION = YES; 147 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 148 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 149 | CLANG_WARN_UNREACHABLE_CODE = YES; 150 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 151 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 152 | COPY_PHASE_STRIP = NO; 153 | DEBUG_INFORMATION_FORMAT = dwarf; 154 | ENABLE_STRICT_OBJC_MSGSEND = YES; 155 | ENABLE_TESTABILITY = YES; 156 | GCC_C_LANGUAGE_STANDARD = gnu99; 157 | GCC_DYNAMIC_NO_PIC = NO; 158 | GCC_NO_COMMON_BLOCKS = YES; 159 | GCC_OPTIMIZATION_LEVEL = 0; 160 | GCC_PREPROCESSOR_DEFINITIONS = ( 161 | "DEBUG=1", 162 | "$(inherited)", 163 | ); 164 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 165 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 166 | GCC_WARN_UNDECLARED_SELECTOR = YES; 167 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 168 | GCC_WARN_UNUSED_FUNCTION = YES; 169 | GCC_WARN_UNUSED_VARIABLE = YES; 170 | IPHONEOS_DEPLOYMENT_TARGET = 9.1; 171 | MTL_ENABLE_DEBUG_INFO = YES; 172 | ONLY_ACTIVE_ARCH = YES; 173 | SDKROOT = iphoneos; 174 | }; 175 | name = Debug; 176 | }; 177 | 5DFE59191C0E9C0800784FDF /* Release */ = { 178 | isa = XCBuildConfiguration; 179 | buildSettings = { 180 | ALWAYS_SEARCH_USER_PATHS = NO; 181 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 182 | CLANG_CXX_LIBRARY = "libc++"; 183 | CLANG_ENABLE_MODULES = YES; 184 | CLANG_ENABLE_OBJC_ARC = YES; 185 | CLANG_WARN_BOOL_CONVERSION = YES; 186 | CLANG_WARN_CONSTANT_CONVERSION = YES; 187 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 188 | CLANG_WARN_EMPTY_BODY = YES; 189 | CLANG_WARN_ENUM_CONVERSION = YES; 190 | CLANG_WARN_INFINITE_RECURSION = YES; 191 | CLANG_WARN_INT_CONVERSION = YES; 192 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 193 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 194 | CLANG_WARN_UNREACHABLE_CODE = YES; 195 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 196 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 197 | COPY_PHASE_STRIP = NO; 198 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 199 | ENABLE_NS_ASSERTIONS = NO; 200 | ENABLE_STRICT_OBJC_MSGSEND = YES; 201 | GCC_C_LANGUAGE_STANDARD = gnu99; 202 | GCC_NO_COMMON_BLOCKS = YES; 203 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 204 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 205 | GCC_WARN_UNDECLARED_SELECTOR = YES; 206 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 207 | GCC_WARN_UNUSED_FUNCTION = YES; 208 | GCC_WARN_UNUSED_VARIABLE = YES; 209 | IPHONEOS_DEPLOYMENT_TARGET = 9.1; 210 | MTL_ENABLE_DEBUG_INFO = NO; 211 | SDKROOT = iphoneos; 212 | VALIDATE_PRODUCT = YES; 213 | }; 214 | name = Release; 215 | }; 216 | 5DFE591B1C0E9C0800784FDF /* Debug */ = { 217 | isa = XCBuildConfiguration; 218 | buildSettings = { 219 | HEADER_SEARCH_PATHS = ( 220 | "$(inherited)", 221 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, 222 | ); 223 | OTHER_LDFLAGS = "-ObjC"; 224 | PRODUCT_NAME = "$(TARGET_NAME)"; 225 | SKIP_INSTALL = YES; 226 | }; 227 | name = Debug; 228 | }; 229 | 5DFE591C1C0E9C0800784FDF /* Release */ = { 230 | isa = XCBuildConfiguration; 231 | buildSettings = { 232 | HEADER_SEARCH_PATHS = ( 233 | "$(inherited)", 234 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, 235 | ); 236 | OTHER_LDFLAGS = "-ObjC"; 237 | PRODUCT_NAME = "$(TARGET_NAME)"; 238 | SKIP_INSTALL = YES; 239 | }; 240 | name = Release; 241 | }; 242 | /* End XCBuildConfiguration section */ 243 | 244 | /* Begin XCConfigurationList section */ 245 | 5DFE590C1C0E9C0800784FDF /* Build configuration list for PBXProject "DeviceBattery" */ = { 246 | isa = XCConfigurationList; 247 | buildConfigurations = ( 248 | 5DFE59181C0E9C0800784FDF /* Debug */, 249 | 5DFE59191C0E9C0800784FDF /* Release */, 250 | ); 251 | defaultConfigurationIsVisible = 0; 252 | defaultConfigurationName = Release; 253 | }; 254 | 5DFE591A1C0E9C0800784FDF /* Build configuration list for PBXNativeTarget "DeviceBattery" */ = { 255 | isa = XCConfigurationList; 256 | buildConfigurations = ( 257 | 5DFE591B1C0E9C0800784FDF /* Debug */, 258 | 5DFE591C1C0E9C0800784FDF /* Release */, 259 | ); 260 | defaultConfigurationIsVisible = 0; 261 | defaultConfigurationName = Release; 262 | }; 263 | /* End XCConfigurationList section */ 264 | }; 265 | rootObject = 5DFE59091C0E9C0800784FDF /* Project object */; 266 | } 267 | -------------------------------------------------------------------------------- /ios/DeviceBattery.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ios/DeviceBattery.xcodeproj/project.xcworkspace/xcuserdata/ajwhite.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robinpowered/react-native-device-battery/ead638e641aeccf85af76bd9b4d2aded448df352/ios/DeviceBattery.xcodeproj/project.xcworkspace/xcuserdata/ajwhite.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /ios/DeviceBattery.xcodeproj/xcuserdata/ajwhite.xcuserdatad/xcschemes/DeviceBattery.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 34 | 35 | 45 | 46 | 52 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 70 | 71 | 72 | 73 | 75 | 76 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /ios/DeviceBattery.xcodeproj/xcuserdata/ajwhite.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | DeviceBattery.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 5DFE59101C0E9C0800784FDF 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /ios/DeviceBattery/DeviceBattery.h: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #if __has_include() 4 | #import 5 | #import 6 | #else // backward compat for rn pre 0.40 7 | #import "RCTBridgeModule.h" 8 | #import "RCTEventEmitter.h" 9 | #endif 10 | 11 | @interface DeviceBattery : RCTEventEmitter 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /ios/DeviceBattery/DeviceBattery.m: -------------------------------------------------------------------------------- 1 | #import "DeviceBattery.h" 2 | 3 | @implementation DeviceBattery 4 | RCT_EXPORT_MODULE(); 5 | 6 | static const NSString *BATTERY_CHANGE_EVENT = @"batteryChanged"; 7 | 8 | - (instancetype)init 9 | { 10 | if((self = [super init])) { 11 | dispatch_async(dispatch_get_main_queue(), ^{ 12 | [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 13 | }); 14 | 15 | [[NSNotificationCenter defaultCenter] addObserver:self 16 | selector:@selector(batteryLevelChanged:) 17 | name:UIDeviceBatteryLevelDidChangeNotification 18 | object:nil]; 19 | [[NSNotificationCenter defaultCenter] addObserver:self 20 | selector:@selector(batteryLevelChanged:) 21 | name:UIDeviceBatteryStateDidChangeNotification 22 | object:nil]; 23 | } 24 | return self; 25 | } 26 | 27 | - (void)dealloc 28 | { 29 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 30 | } 31 | 32 | - (NSArray *)supportedEvents { 33 | return @[BATTERY_CHANGE_EVENT]; 34 | } 35 | 36 | - (NSDictionary *)constantsToExport 37 | { 38 | return @{@"BATTERY_CHANGE_EVENT": BATTERY_CHANGE_EVENT}; 39 | } 40 | 41 | // UIDevice (UIKit) may only be accessed on main thread 42 | +(BOOL)requiresMainQueueSetup 43 | { 44 | return YES; 45 | } 46 | -(dispatch_queue_t)methodQueue 47 | { 48 | return dispatch_get_main_queue(); 49 | } 50 | 51 | RCT_REMAP_METHOD(isCharging, 52 | isChargingResolver:(RCTPromiseResolveBlock)resolve 53 | isChargingRejecter:(RCTPromiseRejectBlock)reject) { 54 | UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState; 55 | if (batteryState == UIDeviceBatteryStateCharging) { 56 | resolve(@YES); 57 | } else { 58 | resolve(@NO); 59 | } 60 | } 61 | 62 | RCT_REMAP_METHOD(getBatteryLevel, 63 | getBatteryLevelResolver:(RCTPromiseResolveBlock)resolve 64 | getBatteryLevelRejecter:(RCTPromiseRejectBlock)reject) 65 | { 66 | float batteryLevel = [UIDevice currentDevice].batteryLevel; 67 | resolve(@(batteryLevel)); 68 | } 69 | 70 | -(void)batteryLevelChanged:(NSNotification*)notification { 71 | UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState; 72 | NSMutableDictionary* payload = [NSMutableDictionary dictionaryWithCapacity:2]; 73 | bool isCharging = batteryState == UIDeviceBatteryStateCharging; 74 | float batteryLevel = [UIDevice currentDevice].batteryLevel; 75 | 76 | [payload setObject:[NSNumber numberWithBool:isCharging] forKey:@"charging"]; 77 | [payload setObject:[NSNumber numberWithFloat:batteryLevel] forKey:@"level"]; 78 | 79 | [self sendEventWithName:BATTERY_CHANGE_EVENT body:payload]; 80 | } 81 | 82 | @end 83 | 84 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-device-battery", 3 | "version": "3.0.0", 4 | "description": "Observe battery state changes in your react native application", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+ssh://git@github.com/robinpowered/react-native-device-battery.git" 12 | }, 13 | "keywords": [ 14 | "react", 15 | "native", 16 | "battery", 17 | "device" 18 | ], 19 | "author": "Atticus White (http://atticuswhite.com/)", 20 | "license": "MIT", 21 | "bugs": { 22 | "url": "https://github.com/robinpowered/react-native-device-battery/issues" 23 | }, 24 | "homepage": "https://github.com/robinpowered/react-native-device-battery#readme" 25 | } 26 | -------------------------------------------------------------------------------- /react-native-device-battery.podspec: -------------------------------------------------------------------------------- 1 | require 'json' 2 | 3 | package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) 4 | 5 | Pod::Spec.new do |s| 6 | s.name = package['name'] 7 | s.version = package['version'] 8 | s.summary = package['description'] 9 | s.license = package['license'] 10 | 11 | s.authors = package['author'] 12 | s.homepage = package['homepage'] 13 | s.platforms = { :ios => "9.0", :osx => "10.14" } 14 | 15 | s.source = { :git => "https://github.com/robinpowered/react-native-device-battery.git", :tag => "v#{s.version}" } 16 | s.source_files = "ios/**/*.{h,m}" 17 | 18 | s.dependency 'React' 19 | end 20 | --------------------------------------------------------------------------------