Skip to main content

Power state

getPowerState() returns a PowerState:

FieldTypeMeaning
batteryLevelnumber | undefinedCharge from 0 to 1. undefined when the platform cannot tell.
batteryState'unknown' | 'unplugged' | 'charging' | 'full'Whether the battery charges. full means plugged in with a full battery.
lowPowerModebooleanLow Power Mode on iOS, Battery Saver on Android.
const { batteryLevel, batteryState, lowPowerMode } = DeviceInfo.getPowerState()
const percent = batteryLevel === undefined ? undefined : Math.round(batteryLevel * 100)

Observe changes​

const subscription = DeviceInfo.addOnPowerStateChangedListener((state) => {
console.log(state.batteryLevel, state.batteryState, state.lowPowerMode)
})

// later
subscription.remove()

In a component, add the listener in an effect and remove it in the cleanup:

const [power, setPower] = useState(() => DeviceInfo.getPowerState())

useEffect(() => {
const subscription = DeviceInfo.addOnPowerStateChangedListener(setPower)
return () => subscription.remove()
}, [])

When the listener runs​

  • Only when a PowerState field differs from the last state it reported. Android battery broadcasts also fire for voltage and temperature changes; those do not reach the listener.
  • On the main thread, which is the thread NitroUI runs JavaScript on. iOS posts Low Power Mode changes on a background thread; the module delivers them on the main queue.
  • Not with the current state when you subscribe. Read getPowerState() for the initial value, as the effect above does.

What it costs​

All listeners share one native observer. It starts with the first listener and stops when the last one is removed, so an app without listeners observes nothing. Calling remove() twice is harmless.

PlatformObserves
iOSbatteryLevelDidChangeNotification, batteryStateDidChangeNotification, NSProcessInfoPowerStateDidChange
AndroidACTION_BATTERY_CHANGED and ACTION_POWER_SAVE_MODE_CHANGED broadcasts

Platform notes​

  • iOS simulator: batteryLevel is undefined and batteryState is unknown.
  • iOS: the first read turns on UIDevice.isBatteryMonitoringEnabled and leaves it on; without it, iOS reports -1 and unknown.
  • Android: a device that is plugged in but not charging, because it is full or held at a charge limit, reports full.