Power state
getPowerState() returns a PowerState:
| Field | Type | Meaning |
|---|---|---|
batteryLevel | number | undefined | Charge 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. |
lowPowerMode | boolean | Low 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
PowerStatefield 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.
| Platform | Observes |
|---|---|
| iOS | batteryLevelDidChangeNotification, batteryStateDidChangeNotification, NSProcessInfoPowerStateDidChange |
| Android | ACTION_BATTERY_CHANGED and ACTION_POWER_SAVE_MODE_CHANGED broadcasts |
Platform notes
- iOS simulator:
batteryLevelisundefinedandbatteryStateisunknown. - iOS: the first read turns on
UIDevice.isBatteryMonitoringEnabledand leaves it on; without it, iOS reports-1andunknown. - Android: a device that is plugged in but not charging, because it is full or held at a charge limit, reports
full.