Skip to main content

Introduction

React Native Background Guardian provides a comprehensive API to prevent Android from killing background processes. The library offers methods for managing wake locks, battery optimizations, and OEM-specific settings.

Installation

import BackgroundGuardian, {
  acquireWakeLock,
  releaseWakeLock,
  isIgnoringBatteryOptimizations,
  // ... other named exports
} from 'react-native-background-guardian';

Import Options

You can use either the default export or named exports:
// Option 1: Default export (object-style API)
import BackgroundGuardian from 'react-native-background-guardian';
await BackgroundGuardian.acquireWakeLock('MyTask');

// Option 2: Named exports (functional API)
import { acquireWakeLock, releaseWakeLock } from 'react-native-background-guardian';
await acquireWakeLock('MyTask');
await releaseWakeLock();

TypeScript Support

The library is written in TypeScript and includes complete type definitions. All functions return typed promises:
const isHeld: boolean = await isWakeLockHeld();
const manufacturer: string | null = await getDeviceManufacturer();

Exported Interfaces

The library exports several TypeScript interfaces for type-safe development:
// Main API interface
interface BackgroundGuardianInterface {
  acquireWakeLock: (tag?: string, timeout?: number) => Promise<boolean>;
  releaseWakeLock: () => Promise<boolean>;
  isWakeLockHeld: () => Promise<boolean>;
  // ... all other methods
}

// Device information
interface DeviceInfo {
  manufacturer: string | null;
}

// Additional utility types (for internal use)
interface WakeLockResult {
  success: boolean;
}

interface BatteryOptimizationStatus {
  isIgnoring: boolean;
}

API Categories

Wake Lock Management

Control CPU wake locks to keep background tasks running:

Screen Wake Lock

Keep the screen on while the app is in the foreground:

Battery Optimization

Manage battery optimization exemptions:

Power Management

Monitor device power states:

OEM Settings

Access manufacturer-specific battery settings:

Platform Behavior

Most APIs are Android-specific:
  • Android: Full functionality as documented
  • iOS: Most methods are no-ops that return safe default values
iOS handles background execution differently through Background Modes configured in Xcode.

Basic Usage Pattern

import { acquireWakeLock, releaseWakeLock } from 'react-native-background-guardian';

// Before starting background work
const acquired = await acquireWakeLock('MyBackgroundTask');

if (acquired) {
  try {
    // Perform your background work
    await doBackgroundWork();
  } finally {
    // Always release when done
    await releaseWakeLock();
  }
}

Error Handling

All methods return boolean promises that resolve to false on error rather than throwing exceptions. This makes error handling straightforward:
const success = await acquireWakeLock();
if (!success) {
  console.error('Failed to acquire wake lock');
}