0
# Battery and Power
1
2
Battery status and power management information for power-aware applications and battery optimization. Critical for apps that need to adapt behavior based on battery state.
3
4
## Capabilities
5
6
### Battery Level
7
8
Get current battery level information.
9
10
```typescript { .api }
11
/**
12
* Get battery level (async)
13
* @returns Promise resolving to battery level as decimal (0.0 to 1.0)
14
* @platforms Android, iOS, Windows, Web
15
*/
16
function getBatteryLevel(): Promise<number>;
17
18
/**
19
* Get battery level (sync)
20
* @returns Battery level as decimal (0.0 to 1.0)
21
* @platforms Android, iOS, Windows, Web
22
*/
23
function getBatteryLevelSync(): number;
24
25
/**
26
* Check if battery level is considered low
27
* @param level - Battery level to check
28
* @returns True if battery level is low
29
* @platforms All (utility function)
30
*/
31
function isLowBatteryLevel(level: number): boolean;
32
```
33
34
**Usage Examples:**
35
36
```typescript
37
import { getBatteryLevel, isLowBatteryLevel } from 'react-native-device-info';
38
39
// Get battery information
40
const batteryLevel = await getBatteryLevel();
41
const batteryPercent = Math.round(batteryLevel * 100);
42
43
console.log(`Battery Level: ${batteryPercent}%`);
44
45
// Check for low battery
46
const isLowBattery = isLowBatteryLevel(batteryLevel);
47
console.log(`Low Battery: ${isLowBattery}`);
48
49
// Battery-aware features
50
if (isLowBattery) {
51
console.log('Enabling power saving mode');
52
// Reduce background tasks
53
// Lower animation frame rates
54
// Disable location updates
55
}
56
57
// Feature gating based on battery level
58
const canPerformIntensiveTask = batteryLevel > 0.20; // 20%
59
if (!canPerformIntensiveTask) {
60
console.log('Deferring intensive tasks due to low battery');
61
}
62
```
63
64
### Battery Charging Status
65
66
Check if device is currently charging.
67
68
```typescript { .api }
69
/**
70
* Check if battery is charging (async)
71
* @returns Promise resolving to true if charging
72
* @platforms Android, iOS, Windows, Web
73
*/
74
function isBatteryCharging(): Promise<boolean>;
75
76
/**
77
* Check if battery is charging (sync)
78
* @returns True if battery is charging
79
* @platforms Android, iOS, Windows, Web
80
*/
81
function isBatteryChargingSync(): boolean;
82
```
83
84
**Usage Examples:**
85
86
```typescript
87
import { isBatteryCharging, getBatteryLevel } from 'react-native-device-info';
88
89
// Check charging status
90
const isCharging = await isBatteryCharging();
91
const batteryLevel = await getBatteryLevel();
92
93
console.log(`Charging: ${isCharging}`);
94
95
// Adaptive behavior based on charging state
96
if (isCharging) {
97
console.log('Device is charging - enabling high-performance features');
98
// Enable background sync
99
// Increase animation quality
100
// Allow intensive operations
101
} else if (batteryLevel < 0.15) {
102
console.log('Device is not charging and battery is low - enabling power saving');
103
// Reduce background activity
104
// Lower screen brightness
105
// Disable non-essential features
106
}
107
108
// Charging time estimation (rough)
109
if (isCharging && batteryLevel < 1.0) {
110
const remainingCapacity = 1.0 - batteryLevel;
111
const estimatedChargingHours = remainingCapacity * 2; // Rough estimate
112
console.log(`Estimated charging time: ${Math.round(estimatedChargingHours * 60)} minutes`);
113
}
114
```
115
116
### Power State Information
117
118
Get comprehensive power state information including battery details and power mode.
119
120
```typescript { .api }
121
/**
122
* Get power state information (async)
123
* @returns Promise resolving to power state object
124
* @platforms iOS, Android, Windows, Web
125
*/
126
function getPowerState(): Promise<Partial<PowerState>>;
127
128
/**
129
* Get power state information (sync)
130
* @returns Power state object
131
* @platforms iOS, Android, Windows, Web
132
*/
133
function getPowerStateSync(): Partial<PowerState>;
134
135
interface PowerState {
136
batteryLevel: number;
137
batteryState: BatteryState;
138
lowPowerMode: boolean;
139
[key: string]: any;
140
}
141
142
type BatteryState = 'unknown' | 'unplugged' | 'charging' | 'full';
143
```
144
145
**Usage Examples:**
146
147
```typescript
148
import { getPowerState } from 'react-native-device-info';
149
150
// Get comprehensive power information
151
const powerState = await getPowerState();
152
153
console.log('Power State:', {
154
batteryLevel: `${Math.round(powerState.batteryLevel * 100)}%`,
155
batteryState: powerState.batteryState,
156
lowPowerMode: powerState.lowPowerMode
157
});
158
159
// Adapt app behavior to power state
160
switch (powerState.batteryState) {
161
case 'charging':
162
console.log('Device is charging - full performance available');
163
break;
164
case 'full':
165
console.log('Battery is full');
166
break;
167
case 'unplugged':
168
console.log('Device is unplugged - consider power saving');
169
break;
170
case 'unknown':
171
default:
172
console.log('Battery state unknown');
173
break;
174
}
175
176
// Low power mode adaptation
177
if (powerState.lowPowerMode) {
178
console.log('Low power mode is enabled - reducing app activity');
179
// Disable animations
180
// Reduce background tasks
181
// Lower refresh rates
182
// Pause non-essential services
183
}
184
185
// Battery health monitoring
186
const batteryHealth = {
187
level: powerState.batteryLevel,
188
state: powerState.batteryState,
189
isHealthy: powerState.batteryLevel > 0.8 || powerState.batteryState === 'charging',
190
needsOptimization: powerState.lowPowerMode || powerState.batteryLevel < 0.2
191
};
192
193
console.log('Battery Health:', batteryHealth);
194
```
195
196
### iOS-Specific Power Features
197
198
iOS-specific power and display features.
199
200
```typescript { .api }
201
/**
202
* Get screen brightness (async)
203
* @returns Promise resolving to brightness level (0.0 to 1.0)
204
* @platforms iOS
205
*/
206
function getBrightness(): Promise<number>;
207
208
/**
209
* Get screen brightness (sync)
210
* @returns Brightness level (0.0 to 1.0)
211
* @platforms iOS
212
*/
213
function getBrightnessSync(): number;
214
```
215
216
**Usage Examples:**
217
218
```typescript
219
import { getBrightness } from 'react-native-device-info';
220
import { Platform } from 'react-native';
221
222
if (Platform.OS === 'ios') {
223
// Get screen brightness
224
const brightness = await getBrightness();
225
const brightnessPercent = Math.round(brightness * 100);
226
227
console.log(`Screen Brightness: ${brightnessPercent}%`);
228
229
// Power optimization based on brightness
230
if (brightness > 0.8) {
231
console.log('High brightness detected - screen is using significant power');
232
}
233
234
// Adaptive UI based on brightness
235
const isDarkEnvironment = brightness < 0.3;
236
if (isDarkEnvironment) {
237
console.log('Low brightness suggests dark environment - consider dark theme');
238
}
239
}
240
```
241
242
### Power Management Utilities
243
244
Utility functions for power-aware application behavior.
245
246
**Usage Examples:**
247
248
```typescript
249
import {
250
getBatteryLevel,
251
isBatteryCharging,
252
getPowerState,
253
isLowBatteryLevel
254
} from 'react-native-device-info';
255
256
// Power management class
257
class PowerManager {
258
static async getPowerProfile(): Promise<'high' | 'balanced' | 'power_saver'> {
259
const powerState = await getPowerState();
260
const isCharging = await isBatteryCharging();
261
262
if (isCharging || powerState.batteryLevel > 0.5) {
263
return 'high';
264
} else if (powerState.batteryLevel > 0.2 && !powerState.lowPowerMode) {
265
return 'balanced';
266
} else {
267
return 'power_saver';
268
}
269
}
270
271
static async getRecommendedSettings() {
272
const profile = await this.getPowerProfile();
273
const powerState = await getPowerState();
274
275
const settings = {
276
animationsEnabled: profile !== 'power_saver',
277
backgroundRefreshInterval: profile === 'high' ? 30 : profile === 'balanced' ? 60 : 300,
278
locationAccuracy: profile === 'high' ? 'high' : 'low',
279
imageQuality: profile === 'power_saver' ? 'low' : 'high',
280
maxConcurrentOperations: profile === 'high' ? 4 : profile === 'balanced' ? 2 : 1
281
};
282
283
return { profile, settings, powerState };
284
}
285
286
static async monitorPowerChanges(callback: (powerInfo: any) => void) {
287
// This would typically be implemented with event listeners
288
// For demonstration, showing the data structure
289
setInterval(async () => {
290
const powerInfo = await this.getRecommendedSettings();
291
callback(powerInfo);
292
}, 60000); // Check every minute
293
}
294
}
295
296
// Usage
297
const powerSettings = await PowerManager.getRecommendedSettings();
298
console.log('Power Settings:', powerSettings);
299
300
// Apply power-aware settings
301
if (powerSettings.profile === 'power_saver') {
302
console.log('Applying power saving settings');
303
// Reduce app functionality
304
// Increase update intervals
305
// Disable non-essential features
306
}
307
308
// Monitor power changes
309
PowerManager.monitorPowerChanges((powerInfo) => {
310
console.log('Power state changed:', powerInfo.profile);
311
// Update app behavior based on new power state
312
});
313
```
314
315
### Battery Analytics
316
317
Track battery usage patterns for analytics and optimization.
318
319
**Usage Examples:**
320
321
```typescript
322
import { getBatteryLevel, getPowerState } from 'react-native-device-info';
323
324
// Battery analytics class
325
class BatteryAnalytics {
326
static batteryHistory: Array<{timestamp: number, level: number, state: string}> = [];
327
328
static async recordBatteryState() {
329
const powerState = await getPowerState();
330
const record = {
331
timestamp: Date.now(),
332
level: powerState.batteryLevel,
333
state: powerState.batteryState || 'unknown'
334
};
335
336
this.batteryHistory.push(record);
337
338
// Keep only last 24 hours of data
339
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
340
this.batteryHistory = this.batteryHistory.filter(r => r.timestamp > oneDayAgo);
341
342
return record;
343
}
344
345
static getBatteryUsageRate(): number {
346
if (this.batteryHistory.length < 2) return 0;
347
348
const recent = this.batteryHistory.slice(-2);
349
const timeDiff = (recent[1].timestamp - recent[0].timestamp) / 1000 / 60; // minutes
350
const levelDiff = recent[0].level - recent[1].level; // positive = drain
351
352
return levelDiff / timeDiff; // % per minute
353
}
354
355
static getEstimatedTimeRemaining(): number {
356
const currentLevel = this.batteryHistory[this.batteryHistory.length - 1]?.level || 0;
357
const drainRate = this.getBatteryUsageRate();
358
359
if (drainRate <= 0) return Infinity; // Not draining or charging
360
361
return currentLevel / drainRate; // minutes remaining
362
}
363
}
364
365
// Usage
366
await BatteryAnalytics.recordBatteryState();
367
368
// Later...
369
const usageRate = BatteryAnalytics.getBatteryUsageRate();
370
const timeRemaining = BatteryAnalytics.getEstimatedTimeRemaining();
371
372
console.log(`Battery drain rate: ${usageRate.toFixed(3)}% per minute`);
373
console.log(`Estimated time remaining: ${Math.round(timeRemaining)} minutes`);
374
```
375
376
## Types
377
378
```typescript { .api }
379
type BatteryState = 'unknown' | 'unplugged' | 'charging' | 'full';
380
381
interface PowerState {
382
batteryLevel: number;
383
batteryState: BatteryState;
384
lowPowerMode: boolean;
385
[key: string]: any;
386
}
387
```