CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-native-device-info

Get device information using react-native

Pending
Overview
Eval results
Files

battery-power.mddocs/

Battery and Power

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.

Capabilities

Battery Level

Get current battery level information.

/**
 * Get battery level (async)
 * @returns Promise resolving to battery level as decimal (0.0 to 1.0)
 * @platforms Android, iOS, Windows, Web
 */
function getBatteryLevel(): Promise<number>;

/**
 * Get battery level (sync)
 * @returns Battery level as decimal (0.0 to 1.0)
 * @platforms Android, iOS, Windows, Web
 */
function getBatteryLevelSync(): number;

/**
 * Check if battery level is considered low
 * @param level - Battery level to check
 * @returns True if battery level is low
 * @platforms All (utility function)
 */
function isLowBatteryLevel(level: number): boolean;

Usage Examples:

import { getBatteryLevel, isLowBatteryLevel } from 'react-native-device-info';

// Get battery information
const batteryLevel = await getBatteryLevel();
const batteryPercent = Math.round(batteryLevel * 100);

console.log(`Battery Level: ${batteryPercent}%`);

// Check for low battery
const isLowBattery = isLowBatteryLevel(batteryLevel);
console.log(`Low Battery: ${isLowBattery}`);

// Battery-aware features
if (isLowBattery) {
  console.log('Enabling power saving mode');
  // Reduce background tasks
  // Lower animation frame rates
  // Disable location updates
}

// Feature gating based on battery level
const canPerformIntensiveTask = batteryLevel > 0.20; // 20%
if (!canPerformIntensiveTask) {
  console.log('Deferring intensive tasks due to low battery');
}

Battery Charging Status

Check if device is currently charging.

/**
 * Check if battery is charging (async)
 * @returns Promise resolving to true if charging
 * @platforms Android, iOS, Windows, Web
 */
function isBatteryCharging(): Promise<boolean>;

/**
 * Check if battery is charging (sync)
 * @returns True if battery is charging
 * @platforms Android, iOS, Windows, Web
 */
function isBatteryChargingSync(): boolean;

Usage Examples:

import { isBatteryCharging, getBatteryLevel } from 'react-native-device-info';

// Check charging status
const isCharging = await isBatteryCharging();
const batteryLevel = await getBatteryLevel();

console.log(`Charging: ${isCharging}`);

// Adaptive behavior based on charging state
if (isCharging) {
  console.log('Device is charging - enabling high-performance features');
  // Enable background sync
  // Increase animation quality
  // Allow intensive operations
} else if (batteryLevel < 0.15) {
  console.log('Device is not charging and battery is low - enabling power saving');
  // Reduce background activity
  // Lower screen brightness
  // Disable non-essential features
}

// Charging time estimation (rough)
if (isCharging && batteryLevel < 1.0) {
  const remainingCapacity = 1.0 - batteryLevel;
  const estimatedChargingHours = remainingCapacity * 2; // Rough estimate
  console.log(`Estimated charging time: ${Math.round(estimatedChargingHours * 60)} minutes`);
}

Power State Information

Get comprehensive power state information including battery details and power mode.

/**
 * Get power state information (async)
 * @returns Promise resolving to power state object
 * @platforms iOS, Android, Windows, Web
 */
function getPowerState(): Promise<Partial<PowerState>>;

/**
 * Get power state information (sync)
 * @returns Power state object
 * @platforms iOS, Android, Windows, Web
 */
function getPowerStateSync(): Partial<PowerState>;

interface PowerState {
  batteryLevel: number;
  batteryState: BatteryState;
  lowPowerMode: boolean;
  [key: string]: any;
}

type BatteryState = 'unknown' | 'unplugged' | 'charging' | 'full';

Usage Examples:

import { getPowerState } from 'react-native-device-info';

// Get comprehensive power information
const powerState = await getPowerState();

console.log('Power State:', {
  batteryLevel: `${Math.round(powerState.batteryLevel * 100)}%`,
  batteryState: powerState.batteryState,
  lowPowerMode: powerState.lowPowerMode
});

// Adapt app behavior to power state
switch (powerState.batteryState) {
  case 'charging':
    console.log('Device is charging - full performance available');
    break;
  case 'full':
    console.log('Battery is full');
    break;
  case 'unplugged':
    console.log('Device is unplugged - consider power saving');
    break;
  case 'unknown':
  default:
    console.log('Battery state unknown');
    break;
}

// Low power mode adaptation
if (powerState.lowPowerMode) {
  console.log('Low power mode is enabled - reducing app activity');
  // Disable animations
  // Reduce background tasks
  // Lower refresh rates
  // Pause non-essential services
}

// Battery health monitoring
const batteryHealth = {
  level: powerState.batteryLevel,
  state: powerState.batteryState,
  isHealthy: powerState.batteryLevel > 0.8 || powerState.batteryState === 'charging',
  needsOptimization: powerState.lowPowerMode || powerState.batteryLevel < 0.2
};

console.log('Battery Health:', batteryHealth);

iOS-Specific Power Features

iOS-specific power and display features.

/**
 * Get screen brightness (async)
 * @returns Promise resolving to brightness level (0.0 to 1.0)
 * @platforms iOS
 */
function getBrightness(): Promise<number>;

/**
 * Get screen brightness (sync)
 * @returns Brightness level (0.0 to 1.0)
 * @platforms iOS
 */
function getBrightnessSync(): number;

Usage Examples:

import { getBrightness } from 'react-native-device-info';
import { Platform } from 'react-native';

if (Platform.OS === 'ios') {
  // Get screen brightness
  const brightness = await getBrightness();
  const brightnessPercent = Math.round(brightness * 100);
  
  console.log(`Screen Brightness: ${brightnessPercent}%`);
  
  // Power optimization based on brightness
  if (brightness > 0.8) {
    console.log('High brightness detected - screen is using significant power');
  }
  
  // Adaptive UI based on brightness
  const isDarkEnvironment = brightness < 0.3;
  if (isDarkEnvironment) {
    console.log('Low brightness suggests dark environment - consider dark theme');
  }
}

Power Management Utilities

Utility functions for power-aware application behavior.

Usage Examples:

import { 
  getBatteryLevel, 
  isBatteryCharging, 
  getPowerState,
  isLowBatteryLevel 
} from 'react-native-device-info';

// Power management class
class PowerManager {
  static async getPowerProfile(): Promise<'high' | 'balanced' | 'power_saver'> {
    const powerState = await getPowerState();
    const isCharging = await isBatteryCharging();
    
    if (isCharging || powerState.batteryLevel > 0.5) {
      return 'high';
    } else if (powerState.batteryLevel > 0.2 && !powerState.lowPowerMode) {
      return 'balanced';
    } else {
      return 'power_saver';
    }
  }
  
  static async getRecommendedSettings() {
    const profile = await this.getPowerProfile();
    const powerState = await getPowerState();
    
    const settings = {
      animationsEnabled: profile !== 'power_saver',
      backgroundRefreshInterval: profile === 'high' ? 30 : profile === 'balanced' ? 60 : 300,
      locationAccuracy: profile === 'high' ? 'high' : 'low',
      imageQuality: profile === 'power_saver' ? 'low' : 'high',
      maxConcurrentOperations: profile === 'high' ? 4 : profile === 'balanced' ? 2 : 1
    };
    
    return { profile, settings, powerState };
  }
  
  static async monitorPowerChanges(callback: (powerInfo: any) => void) {
    // This would typically be implemented with event listeners
    // For demonstration, showing the data structure
    setInterval(async () => {
      const powerInfo = await this.getRecommendedSettings();
      callback(powerInfo);
    }, 60000); // Check every minute
  }
}

// Usage
const powerSettings = await PowerManager.getRecommendedSettings();
console.log('Power Settings:', powerSettings);

// Apply power-aware settings
if (powerSettings.profile === 'power_saver') {
  console.log('Applying power saving settings');
  // Reduce app functionality
  // Increase update intervals
  // Disable non-essential features
}

// Monitor power changes
PowerManager.monitorPowerChanges((powerInfo) => {
  console.log('Power state changed:', powerInfo.profile);
  // Update app behavior based on new power state
});

Battery Analytics

Track battery usage patterns for analytics and optimization.

Usage Examples:

import { getBatteryLevel, getPowerState } from 'react-native-device-info';

// Battery analytics class
class BatteryAnalytics {
  static batteryHistory: Array<{timestamp: number, level: number, state: string}> = [];
  
  static async recordBatteryState() {
    const powerState = await getPowerState();
    const record = {
      timestamp: Date.now(),
      level: powerState.batteryLevel,
      state: powerState.batteryState || 'unknown'
    };
    
    this.batteryHistory.push(record);
    
    // Keep only last 24 hours of data
    const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
    this.batteryHistory = this.batteryHistory.filter(r => r.timestamp > oneDayAgo);
    
    return record;
  }
  
  static getBatteryUsageRate(): number {
    if (this.batteryHistory.length < 2) return 0;
    
    const recent = this.batteryHistory.slice(-2);
    const timeDiff = (recent[1].timestamp - recent[0].timestamp) / 1000 / 60; // minutes
    const levelDiff = recent[0].level - recent[1].level; // positive = drain
    
    return levelDiff / timeDiff; // % per minute
  }
  
  static getEstimatedTimeRemaining(): number {
    const currentLevel = this.batteryHistory[this.batteryHistory.length - 1]?.level || 0;
    const drainRate = this.getBatteryUsageRate();
    
    if (drainRate <= 0) return Infinity; // Not draining or charging
    
    return currentLevel / drainRate; // minutes remaining
  }
}

// Usage
await BatteryAnalytics.recordBatteryState();

// Later...
const usageRate = BatteryAnalytics.getBatteryUsageRate();
const timeRemaining = BatteryAnalytics.getEstimatedTimeRemaining();

console.log(`Battery drain rate: ${usageRate.toFixed(3)}% per minute`);
console.log(`Estimated time remaining: ${Math.round(timeRemaining)} minutes`);

Types

type BatteryState = 'unknown' | 'unplugged' | 'charging' | 'full';

interface PowerState {
  batteryLevel: number;
  batteryState: BatteryState;
  lowPowerMode: boolean;
  [key: string]: any;
}

Install with Tessl CLI

npx tessl i tessl/npm-react-native-device-info

docs

application-information.md

battery-power.md

device-identification.md

hardware-features.md

index.md

memory-storage.md

network-connectivity.md

react-hooks.md

system-information.md

tile.json