Skip to main content

Overview

Acquires a partial wake lock to keep the CPU running while the screen is off. This prevents the Android system from suspending the CPU, allowing background tasks to continue running.
function acquireWakeLock(
  tag?: string,
  timeout?: number
): Promise<boolean>

Parameters

tag
string
default:"BackgroundGuardian"
Optional identifier for the wake lock. Useful for debugging and identifying which component holds the lock in system logs.
timeout
number
default:"86400000"
Optional timeout in milliseconds after which the wake lock will be automatically released. Defaults to 24 hours (86400000ms).

Returns

success
boolean
Promise resolving to true if the wake lock was successfully acquired, false otherwise.

Platform Behavior

PlatformBehavior
AndroidAcquires a PARTIAL_WAKE_LOCK that keeps the CPU running. The library manages a single wake lock - if a wake lock is already held, subsequent calls return true without acquiring another lock.
iOSNo-op that returns true immediately. iOS handles background execution differently through Background Modes.

Important Notes

  • Single Wake Lock Model: The library maintains a single wake lock instance. If you call acquireWakeLock() while a lock is already held, it returns true without creating a duplicate. Always call releaseWakeLock() when your background work is complete.
  • Battery Impact: Holding wake locks prevents the device from sleeping, which can drain battery. Use timeouts and release locks promptly.
  • Permission Required: Requires android.permission.WAKE_LOCK in AndroidManifest.xml (automatically added by the library).

Example Usage

Basic Usage

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

// Acquire wake lock before starting background work
const acquired = await acquireWakeLock('MyBackgroundTask');

if (acquired) {
  // Perform background work
  await doBackgroundWork();
  
  // Release when done
  await releaseWakeLock();
}

With Custom Timeout

// Acquire wake lock with 10-minute timeout
const tenMinutes = 10 * 60 * 1000;
const acquired = await acquireWakeLock('ShortTask', tenMinutes);

if (acquired) {
  await performShortBackgroundTask();
  await releaseWakeLock();
}

With Error Handling

try {
  const acquired = await acquireWakeLock('DataSync');
  
  if (!acquired) {
    console.error('Failed to acquire wake lock');
    return;
  }
  
  await syncData();
} finally {
  // Always release in finally block
  await releaseWakeLock();
}

Checking Before Acquiring

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

const isHeld = await isWakeLockHeld();
if (!isHeld) {
  await acquireWakeLock('MyTask');
}